以下示例显示如何获取由java.time.LocalDate和java.time.YearMonth对象表示的月份长度。这两个类都具有一种称为的方法lengthOfMonth(),该方法返回由这些日期对象表示的月的天数。
package org.nhooo.example.datetime;
import java.time.LocalDate;
import java.time.Month;
import java.time.YearMonth;
public class LengthOfMonth {
public static void main(String[] args) {
// 获取当前日期的月份长度。
LocalDate date = LocalDate.now();
System.out.printf("%s: %d%n%n", date, date.lengthOfMonth());
// 获取年月组合值的月长
// 由YearMonth对象表示。
YearMonth yearMonth = YearMonth.of(2015, Month.FEBRUARY);
System.out.printf("%s: %d%n%n", yearMonth, yearMonth.lengthOfMonth());
// 重复一个过程,得到一年的一个月的时间
// 期。
for (int month = 1; month <= 12; month++) {
yearMonth = YearMonth.of(2010, Month.of(month));
System.out.printf("%s: %d%n", yearMonth, yearMonth.lengthOfMonth());
}
}
}main()上面的方法首先显示如何获取LocalDate对象的月份长度。首先,我们LocalDate使用LocalDate.now()静态工厂方法创建一个对象,该方法返回今天的日期。然后,在下一行上打印出今天日期的月份长度。
下一个代码段使用YearMonth该类。我们首先创建一个YearMonth代表2015年2月的对象。我们使用YearMonth.of()静态工厂方法创建了该对象。然后,我们打印出这些年月组合的月长。
在示例的最后几行中,我们创建了一个for循环,以获取2010年1月至12月的所有月份长度。
这是上面的代码片段的结果:
2015-07-17: 31 2015-02: 28 2010-01: 31 2010-02: 28 2010-03: 31 2010-04: 30 2010-05: 31 2010-06: 30 2010-07: 31 2010-08: 31 2010-09: 30 2010-10: 31 2010-11: 30 2010-12: 31