Java 1.8 LocalDate

更新时间 2023-05-26 17:41:03

LocalDate 是一个日期对象,例如:2014-03-11。它和 LocalTime 一样是个 final 类型对象。下面的例子演示了如何通过加减日,月,年等来计算一个新的日期。

LocalDate, LocalTime, 因为是 final 类型的对象,每一次操作都会返回一个新的时间对象。

LocalDate today = LocalDate.now();
// 今天加一天
LocalDate tomorrow = today.plus(1, ChronoUnit.DAYS);
// 明天减两天
LocalDate yesterday = tomorrow.minusDays(2);

// 2014 年七月的第四天
LocalDate independenceDay = LocalDate.of(2014, Month.JULY, 4);
DayOfWeek dayOfWeek = independenceDay.getDayOfWeek();
System.out.println(dayOfWeek);    // 星期五

也可以直接解析日期字符串,生成 LocalDate 实例。(和 LocalTime 操作一样简单)

DateTimeFormatter germanFormatter =
    DateTimeFormatter
        .ofLocalizedDate(FormatStyle.MEDIUM)
        .withLocale(Locale.GERMAN);

LocalDate xmas = LocalDate.parse("24.12.2014", germanFormatter);
System.out.println(xmas);   // 2014-12-24