Date Classes

Date-Time API 提供了四个类,专门处理日期信息,而不考虑时间或timezone。通过类名称LocalDateYearMonthMonthDayYear来建议使用这些类。

LocalDate

LocalDate代表 ISOcalendar 中的年月日,对于表示没有时间的日期很有用。您可以使用LocalDate跟踪重要事件,例如生日或结婚日期。以下示例使用ofwith方法创建LocalDate的实例:

LocalDate date = LocalDate.of(2000, Month.NOVEMBER, 20);
LocalDate nextWed = date.with(TemporalAdjusters.next(DayOfWeek.WEDNESDAY));

有关TemporalAdjusterinterface的更多信息,请参见Temporal Adjuster

除了常用的方法外,LocalDate类还提供用于获取有关给定日期的信息的 getter 方法。 getDayOfWeek方法返回特定日期所在的星期几。例如,以下代码行返回“ MONDAY”:

DayOfWeek dotw = LocalDate.of(2012, Month.JULY, 9).getDayOfWeek();

下面的示例使用TemporalAdjuster检索特定日期之后的第一个星期三。

LocalDate date = LocalDate.of(2000, Month.NOVEMBER, 20);
TemporalAdjuster adj = TemporalAdjusters.next(DayOfWeek.WEDNESDAY);
LocalDate nextWed = date.with(adj);
System.out.printf("For the date of %s, the next Wednesday is %s.%n",
                  date, nextWed);

运行代码将产生以下结果:

For the date of 2000-11-20, the next Wednesday is 2000-11-22.

期限和期限部分还包含使用LocalDate类的示例。

YearMonth

YearMonth类代表特定年份的月份。下面的示例使用YearMonth\.lengthOfMonth\(\)方法确定若干年和月组合的天数。

YearMonth date = YearMonth.now();
System.out.printf("%s: %d%n", date, date.lengthOfMonth());

YearMonth date2 = YearMonth.of(2010, Month.FEBRUARY);
System.out.printf("%s: %d%n", date2, date2.lengthOfMonth());

YearMonth date3 = YearMonth.of(2012, Month.FEBRUARY);
System.out.printf("%s: %d%n", date3, date3.lengthOfMonth());

此代码的输出如下所示:

2013-06: 30
2010-02: 28
2012-02: 29

MonthDay

MonthDay类代表特定月份的日期,例如 1 月 1 日为元旦。

下面的示例使用MonthDay.isValidYear方法确定 2 月 29 日对于 2010 年是否有效。该调用返回false,确认 2010 年不是 a 年。

MonthDay date = MonthDay.of(Month.FEBRUARY, 29);
boolean validLeapYear = date.isValidYear(2010);

Year

Year类代表一年。下面的示例使用Year.isLeap方法确定给定年份是否为 is 年。呼叫返回true,确认 2012 年为 a 年。

boolean validLeapYear = Year.of(2012).isLeap();