溫馨提示×

java怎么獲得當(dāng)前月

小億
87
2024-09-26 02:05:56
欄目: 編程語言

在Java中,你可以使用java.time包中的YearMonth類和LocalDate類來獲取當(dāng)前月份。以下是兩種方法的示例:

方法1:使用YearMonth

import java.time.YearMonth;

public class Main {
    public static void main(String[] args) {
        YearMonth currentMonth = YearMonth.now();
        System.out.println("當(dāng)前月份: " + currentMonth);
    }
}

方法2:使用LocalDate

import java.time.LocalDate;

public class Main {
    public static void main(String[] args) {
        LocalDate currentDate = LocalDate.now();
        int month = currentDate.getMonthValue();
        System.out.println("當(dāng)前月份: " + month);
    }
}

這兩種方法都會輸出當(dāng)前月份。第一種方法返回一個YearMonth對象,可以直接獲取月份。第二種方法返回一個LocalDate對象,需要調(diào)用getMonthValue()方法來獲取月份。

0