【问题标题】:Getting specific date of the next month with time API使用时间 API 获取下个月的特定日期
【发布时间】:2018-07-27 03:29:58
【问题描述】:

我需要使用 java.time API 找到下个月第二个星期日的日期。我是时间 API 的新手。我试过这段代码:

LocalDate current=LocalDate.now();

这给了我当前日期,但LocalDate 没有任何这样的方法可以让我获得 nextMonth 或类似的东西。请建议。我只需要使用时间 API。

【问题讨论】:

  • Sooo,有一点点searching,我想出了LocalDateTime.now().withDayOfMonth(1).plusMonths(1).with(TemporalAdjusters.next(DayOfWeek.SUNDAY)).with(TemporalAdjusters.next(DayOfWeek.SUNDAY));,它想出了2018-08-12T13:34:15.734,但可能有更简单的方法

标签: java java-time localdate date


【解决方案1】:

这可以使用TemporalAdjuster 来完成,如下所示:

LocalDateTime now = LocalDateTime.now();
System.out.println("First day of next month: " + now.with(TemporalAdjusters.firstDayOfNextMonth()));
System.out.println("First Friday in month: " + now.with(TemporalAdjusters.firstInMonth(DayOfWeek.FRIDAY)));

// Custom temporal adjusters.
TemporalAdjuster secondSundayOfNextMonth = temporal -> {
    LocalDate date = LocalDate.from(temporal).plusMonths(1);
    date = date.with(TemporalAdjusters.dayOfWeekInMonth(2, DayOfWeek.SUNDAY));
    return temporal.with(date);
};
System.out.println("Second sunday of next month: " + now.with(secondSundayOfNextMonth));

【讨论】:

  • 比所要求的更一般(因此更复杂),但很好。我认为周日是被要求的,而你是周六,但提问者可能会解决这个问题。
  • @OleV.V.谢谢!将我的示例更改为使用星期日而不是星期六
  • 当为日期写TemoralAdjuster时,最好使用TemporalAdjusters.ofDateAdjuster()docs.oracle.com/javase/8/docs/api/java/time/temporal/…。作为参考,我还建议对 TemporalAdjustersDayOfWeek 上的方法使用静态导入,因为我觉得结果更易于阅读,
【解决方案2】:

alexander.egger’s answer 是正确的,它向我们展示了我们需要的构建块 (+1)。对于上述问题,我们需要的唯一TemporalAdjuster 是我们从图书馆获得的那个。下面的感觉可能会简单一些:

    LocalDate current = LocalDate.now(ZoneId.of("Pacific/Easter"));
    LocalDate secondSundayOfNextMonth = current.plusMonths(1)
            .with(TemporalAdjusters.dayOfWeekInMonth(2, DayOfWeek.SUNDAY));
    System.out.println("2nd Sunday of next month is " + secondSundayOfNextMonth);

今天运行的输出是:

下个月的第二个星期日是2018-08-12

由于月份在不同时区的开始时间不同,我更愿意将明确的时区指定给LocalDate.now

“Everything Should Be Made as Simple as Possible, But Not Simpler”(我想我是从 Bjarne Stroustrup 那里读到的,但他可能在别处偷了它)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-04-28
    • 1970-01-01
    • 1970-01-01
    • 2011-04-02
    • 1970-01-01
    • 2019-05-14
    • 1970-01-01
    相关资源
    最近更新 更多