JavaFX get first day of next month

  • A+

I'm trying to get the first day of the next month from a LocalDate object but have run into some issues.

I have a datepicker where a user can pick any date they want, without restriction and I need to get the next month's first day, this is what I've thought about doing:

LocalDate localDate = myDatePicker.getValue(); LocalTime startTime = LocalTime.of(0, 0);  LocalDate endDate = LocalDate.of(localDate.getYear(), localDate.getMonthValue() + 1, 0); 

However I see a problem that may occur when choosing the month December, if that happens then the call

LocalDate.of(localDate.getYear(), localDate.getMonthValue() + 1, 0); 

Should fail because I'm passing it a month value of 13. Now I could choose to check if the month value is December and if so I could add 1 to the year and start at 0 like so:

if(localDate.getMonthValue() >= 12)     LocalDate.of(localDate.getYear() + 1, 0, 0); 

However I feel like there must be a way to get around this within the class itself. Does anyone know if my presumptions about passing 13 to LocalDate.of month value will cause an error? If so is there a way to do what I want to do that doesn't look so bad and uses a build in method?


  1. Custom way with :

    • .plusMonths(1) to get the next month
    • .withDayOfMonth(1) to get the first day

      LocalDate localDate = LocalDate.of(2018, 12, 15); LocalDate firstNext = localDate.plusMonths(1).withDayOfMonth(1); // or     firstNext = localDate.withDayOfMonth(1).plusMonths(1); System.out.println(firstNext); //2019-01-01 

  1. Built-in way with :

    • TemporalAdjusters.firstDayOfNextMonth()

      firstNext = localDate.with(TemporalAdjusters.firstDayOfNextMonth());  // does a temporal.with(DAY_OF_MONTH, 1).plus(1, MONTHS); operation 


:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: