Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaFX get first day of next month

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?

like image 393
Joe Avatar asked Nov 26 '25 23:11

Joe


1 Answers

Fortunately, Java makes this really easy with the idea of adjusters and TemporalAdjusters.firstDayOfNextMonth():

import java.time.*;
import java.time.temporal.*;

public class Test {
    public static void main(String[] args) {
        LocalDate date1 = LocalDate.of(2018, 12, 3);
        LocalDate date2 = date1.with(TemporalAdjusters.firstDayOfNextMonth());
        System.out.println(date2); // 2019-01-01
    }
}
like image 124
Jon Skeet Avatar answered Nov 28 '25 15:11

Jon Skeet