Search code examples
javalocaldatetime

Get the month last date


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


Solution

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