获取 Java 8 的最后日期

我可以看到 Java 8 新的日期时间 API 有很多类 LocalDateTime、LocalDate、LocalTime。 我可以得到一年中的第一个日期,例如:

LocalDateTime first = LocalDateTime.of(LocalDate.now().getYear(),1,0);

如何在 Java 8 新的日期时间 API 中获取年份的最后一天?

nanhuathyy98 回答:获取 Java 8 的最后日期

您可以将 TemporalAdjusters.lastDayOfYear()LocalDate#with 一起使用。

演示:

import java.time.LocalDate;
import java.time.temporal.TemporalAdjusters;

public class Main {
    public static void main(String[] args) {
        System.out.println(LocalDate.now().with(TemporalAdjusters.lastDayOfYear()));
    }
}

输出:

2021-12-31

ONLINE DEMO

Trail: Date Time 了解有关现代 Date-Time API 的更多信息。

,

Answer by Avinash 是正确的。

另一种方法是使用 YearMonthDay 类。

我们知道每年的最后一天是 12 月 31 日。

MonthDay december31 = MonthDay.of( Month.DECEMBER,31 ) ;

将该月/日 (MonthDay) 应用于年 (Year) 以确定日期 (LocalDate)。

Year currentYear = Year.now( ZoneId.of( "Africa/Tunis" ) ) ;
LocalDate lastDateOfCurrentYear = currentYear.atMonthDay( december31 ) ; 
本文链接:https://www.f2er.com/23590.html

大家都在问