Reputation: 43
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.
Upvotes: 2
Views: 3311
Reputation: 86276
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).
Upvotes: 2
Reputation: 5300
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));
Upvotes: 4