日期Date


created: 2022-07-17T17:03:37+08:00
updated: 2022-07-17T17:36:30+08:00
tags:

  • DateTimeAPI
  • DateTimeAPI/LocalDate
  • DateTimeAPI/YearMonth
  • DateTimeAPI/MonthDay
  • DateTimeAPI/Year

Date

Date-Time API 提供了四个类,它们专门处理日期信息,而不考虑时间或时区。类名建议使用这些类:LocalDate、YearMonth、MonthDay 和 Year。

The LocalDate Class

LocalDate 表示 ISO 日历中的年月日,可用于表示没有时间的日期。

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

除了常用方法之外,LocalDate 类还提供了获取有关给定日期的信息的 getter 方法。

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);

result

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

The YearMonth Class

YearMonth 类表示特定年份的月份。

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());

result

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

The MonthDay Class

MonthDay 类表示特定月份的某一天,例如 1 月 1 日的元旦。

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

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

The Year Class

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

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

[[日期和时间]]

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值