Search code examples
javadatedayofweeklocaldatedate-manipulation

Java date-manipulation


I'm trying to get a date with a Month number, week of month number and a day of week number I thought this will be easy and did this:

LocalDate nextbookingDate = LocalDate.now().plusYears(1);
nextBookingDate = nextBookingDate.with(Month.of(1));
nextBookingDate = nextBookingDate.with(WeekFields.ISO.weekOfMonth(), 1);
nextBookingDate = nextBookingDate.with(DayOfWeek.of(1));
System.out.println(nextBookingDate); //2019-12-30

nextBookingDateshould be 2020-01-06 because its the first Monday in January.
But why do I get 2019-12-30 and how do I solve this?


Solution

  • It’s not completely clear to me what result you want in general, and why. If I may assume that you want the next date that is an nth some-day-of-week of some month, it’s a little more complicated than your code. EDIT: NorthernSky is correct in the comment under his/her answer that .with(TemporalAdjusters.dayOfWeekInMonth(1, DayOfWeek.MONDAY)) more directly and briefly gets us what we need. This should work:

        ZoneId zone = ZoneId.of("Africa/Bamako");
        LocalDate today = LocalDate.now(zone);
        LocalDate nextBookingDate = today.with(Month.JANUARY)
                .with(TemporalAdjusters.dayOfWeekInMonth(1, DayOfWeek.MONDAY));
        if (nextBookingDate.isBefore(today)) {
            // Take next year instead
            nextBookingDate = today.plusYears(1)
                    .with(Month.JANUARY)
                    .with(TemporalAdjusters.dayOfWeekInMonth(1, DayOfWeek.MONDAY));
        }
    
        System.out.println("Next booking date: " + nextBookingDate);
    

    Output when I ran the code just now, was:

    Next booking date: 2020-01-06

    TemporalAdjusters.dayOfWeekInMonth() will get us the 1st Monday, 3rd Tuesday, etc., of the month. So feed any day of week and any number up to 4 or 5 into this method.

    Please supply your desired time zone where I put Africa/Bamako since it is never the same date in all time zones.

    Link: Documentation of TemporalAdjusters.dayOfWeekInMonth().