温馨提示×

java怎么获得当前月

小亿
81
2024-09-26 02:05:56
栏目: 编程语言

在Java中,你可以使用java.time包中的YearMonth类和LocalDate类来获取当前月份。以下是两种方法的示例:

方法1:使用YearMonth

import java.time.YearMonth;

public class Main {
    public static void main(String[] args) {
        YearMonth currentMonth = YearMonth.now();
        System.out.println("当前月份: " + 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("当前月份: " + month);
    }
}

这两种方法都会输出当前月份。第一种方法返回一个YearMonth对象,可以直接获取月份。第二种方法返回一个LocalDate对象,需要调用getMonthValue()方法来获取月份。

0