系列中的上一篇
当前教程
日期
系列中的下一篇

系列中的上一篇: DayOfWeek 和 Month 枚举

系列中的下一篇: 日期和时间

日期

日期时间 API 提供了四个专门处理日期信息的类,不考虑时间或时区。这些类的使用由类名建议:LocalDateYearMonthMonthDayYear.

 

LocalDate 类

一个 LocalDate 表示 ISO 日历中的年-月-日,对于表示没有时间的日期很有用。您可以使用 LocalDate 来跟踪重大事件,例如出生日期或结婚日期。以下示例使用 of 和 with 方法来创建 LocalDate 的实例

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

有关 TemporalAdjuster 接口的更多信息,请参阅有关 时间调整器 的部分。

除了常用的方法之外,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 类表示特定年份的月份。以下示例使用 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 日的新年。

以下示例使用 isValidYear() 方法来确定 2 月 29 日对于 2010 年是否有效。该调用返回 false,确认 2010 年不是闰年。

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

 

Year 类

Year 类表示年份。以下示例使用 isLeap() 方法来确定给定年份是否为闰年。该调用返回 true,确认 2012 年是闰年。

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

上次更新: 2022 年 1 月 27 日


系列中的上一篇
当前教程
日期
系列中的下一篇

系列中的上一篇: DayOfWeek 和 Month 枚举

系列中的下一篇: 日期和时间