2

I need to find the date of the second Sunday of the next month using java.time API. I am new to time API. I tried this code:

LocalDate current=LocalDate.now();

This is giving me current date but LocalDate does not have any such method where I can get nextMonth or something like that. Please suggest. I need to use time API only.

1
  • Sooo, with a little bit of searching, I came up with LocalDateTime.now().withDayOfMonth(1).plusMonths(1).with(TemporalAdjusters.next(DayOfWeek.SUNDAY)).with(TemporalAdjusters.next(DayOfWeek.SUNDAY)); which comes up with 2018-08-12T13:34:15.734, but there might be a simpler way Commented Jul 27, 2018 at 3:35

2 Answers 2

4

This can be done using a TemporalAdjuster like this:

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));
3
  • A little more general (and therefore a little more complicated) than what was asked for, but fine. I think Sunday was asked for, and you’re giving Saturday, but the asker can probably fix that.
    – Anonymous
    Commented Jul 27, 2018 at 9:02
  • @OleV.V. Thanks! Changed my example to use Sunday instead of Saturday Commented Jul 27, 2018 at 9:23
  • 1
    When writing a TemoralAdjuster for dates, it is best to use TemporalAdjusters.ofDateAdjuster() docs.oracle.com/javase/8/docs/api/java/time/temporal/… . For reference, I also recommend using static imports for the methods on TemporalAdjusters and DayOfWeek as I feel the result is clearer to read, Commented Jul 29, 2018 at 12:59
2

alexander.egger’s answer is correct and shows us the building blocks we need (+1). For the question as stated the only TemporalAdjuster we need is the one we get from the library. The following may feel a bit simpler:

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

Output running today was:

2nd Sunday of next month is 2018-08-12

Since the month doesn’t begin at the same time in different time zones, I have preferred to give explicit time zone to LocalDate.now.

“Everything Should Be Made as Simple as Possible, But Not Simpler” (I think I read it from Bjarne Stroustrup, but he probably stole it somewhere else).

Not the answer you're looking for? Browse other questions tagged or ask your own question.