Adjusting the date in Java 8 Date and Time API
October 23, 2016 Leave a comment
Introduction
We saw a couple of new concepts in the Java 8 Date and Time API on this blog:
- The Instant class
- The LocalDate class
- The LocalTime class
- The LocalDateTime class
All the above classes expose methods called “with” with a couple of overloads. LocalDate, LocalTime and LocalDateTime come with other methods whose names start with “with”, such as withSeconds or withMonth depending on the supported level of time unit. The “with” methods adjust some value of the date-related instances and return a new instance.
Examples
Here’s how you can adjust the day within the month of the LocalDate instance:
LocalDate currentLocalDate = LocalDate.now(); LocalDate dayOfMonthAdjusted = currentLocalDate.withDayOfMonth(12);
The above code will set the day to the 12th of the month of “currentLocalDate” and return the new LocalDate instance “dayOfMonthAdjusted”. Here come some similar adjusters:
LocalDate currentLocalDate = LocalDate.now(); LocalDate dayOfYearAdjusted = currentLocalDate.withDayOfYear(234);
I wrote this post in the year of 2014 so the year value of currentLocalDate was 2014. withDayOfYear will set the day within the year starting from Jan 01. The value of 234 will set the “dayOfYearAdjusted” to 2014-08-22.
The withMonth and withYear modify the month and year values respectively.
LocalTime has similar methods: withHour, withMinute, withSecond and withNano that behave the same way as e.g. withMonth in the case of the LocalDate class.
LocalDateTime has all those methods available: from withYear down to withNano as that class supports these levels of granularity.
TemporalAdjuster
The “with” methods of the previous section are not available for the Instant class. There’s however an interesting overload of “with” for both LocalDate and Instant, the one which accepts a TemporalAdjuster object. The following example will set find the most recent Monday relative to the current day:
LocalDate previousMonday = currentLocalDate.with(TemporalAdjusters.previous(DayOfWeek.MONDAY));
Similarly, you can find the following Monday:
LocalDate nextMonday = currentLocalDate.with(TemporalAdjusters.next(DayOfWeek.MONDAY));
The following code will find the 3rd Monday of the current month:
LocalDate thirdMonday = currentLocalDate.with(TemporalAdjusters.dayOfWeekInMonth(3, DayOfWeek.MONDAY));
TemporalAdjusters has some more interesting constants, the method names are pretty descriptive:
- firstDayOfMonth
- firstDayOfNextMonth
- lastInMonth and firstInMonth which accepts a DayOfWeek enumeration, i.e. you can find the first/last Monday, Tuesday etc. of a given month
- lastDayOfMonth
Read the next part on Java 8 Dates here.
View all posts related to Java here.