3

I have a LocalDateTime object I want to get the last date of the month. So if the localDateTime points to today's date of 29th October. I want to convert it to 31st October
Is there a clean and easy way to do it?
My Thoughts:
One way would be to get the month and then make a switch statement. But that would be the long and tedious approach. Not sure if there is an inbuilt method
to do the same

1

3 Answers 3

6

Use YearMonth.atEndOfMonth

LocalDate date = LocalDate.now();
YearMonth month = YearMonth.from(date);
LocalDate end = month.atEndOfMonth();
5
import java.time.LocalDateTime;
import java.time.temporal.TemporalAdjusters;

public class Main {
    public static void main(String args[]) {
      LocalDateTime a = LocalDateTime.of(2021, 10, 29, 0, 0);
      LocalDateTime b = a.with(TemporalAdjusters.lastDayOfMonth());
      
      System.out.println(a);
      System.out.println(b);
    }
}
1
  • How do I add the endTime of day to the localDateTime. I see an option called LocalTime.MAX but it adds trailing .99999
    – joseph
    Commented Oct 29, 2021 at 16:44
2

You asked:

How do I add the endTime of day to the localDateTime. I see an option called LocalTime.MAX but it adds trailing .99999

Do not use LocalDateTime if you are tracking moments, specific points on the timeline. That class lacks the context of a time zone or offset-from-UTC. For moments, use Instant, OffsetDateTime, or ZonedDateTime.

Represent an entire month with YearMonth.

You should not try to nail down the last moment of the month. That last moment is infinitely divisible. Generally, the best way to define a span of time is the Half-Open approach rather than Fully-Closed. In Half-Open, the beginning is inclusive while the ending is exclusive.

So a day starts with first moment of the day and runs up to, but does not include, the first moment of the next day. A month starts with the first moment of the first day of the month and runs up to, but does not include, the first moment of the first of the next month.

ZoneId z = ZoneId.of( "Asia/Tokyo" ) ;

YearMonth currentMonth = YearMonth.now( z ) ;
YearMonth followingMonth = currentMonth.plusMonths( 1 ) ;

ZonedDateTime start = currentMonth.atDay( 1 ).atStartOfDay( z ) ;
ZonedDateTime end = followingMonth.atDay( 1 ).atStartOfDay( z ) ;

To represent that span of time, add the ThreeTen-Extra library to your project. Use the Interval class with its handy comparison methods such as abuts, overlaps, and contains.

org.threeten.extra.Interval interval = Interval.of( start.toInstant() , end.toInstant() ) ; 

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