Search code examples
javadateformattinglocaldatetime

How to get the start and end of a calendar week as LocalDateTime (java 8)


I want to transform the following String:

private String cw = "35/19" 

into 2 dates.

The start date can be formatted with:

private final DateTimeFormatter startOfWeekFormat = new DateTimeFormatterBuilder()
   .appendPattern("ww/YY")
   .parseDefaulting(WeekFields.ISO.dayOfWeek(), 1)
   .toFormatter();

which when called returns: 26.08.2019

LocalDate.parse(cw, startOfWeekFormat).atStartOfDay();

But I struggle with the end of the week which is basically the start of the next week "36/19".

I tried to add plus 8 days, but that throws an exception:

private final DateTimeFormatter endOfWeekFormat = new DateTimeFormatterBuilder()
    .appendPattern("ww/YY")
    .parseDefaulting(WeekFields.ISO.dayOfWeek(), 8)
    .toFormatter();

Solution

  • LocalDateTime ldt=LocalDate.parse(cw, startOfWeekFormat)
                        .atStartOfDay()
                        .with(TemporalAdjusters.next(DayOfWeek.MONDAY));
    

    Demo:

    import java.time.DayOfWeek;
    import java.time.LocalDate;
    import java.time.LocalDateTime;
    import java.time.format.DateTimeFormatter;
    import java.time.format.DateTimeFormatterBuilder;
    import java.time.temporal.TemporalAdjusters;
    import java.time.temporal.WeekFields;
    
    public class Main {
        public static void main(String[] args) {
            String cw = "35/19";
            final DateTimeFormatter startOfWeekFormat = new DateTimeFormatterBuilder()
                                                .appendPattern("ww/YY")
                                                .parseDefaulting(WeekFields.ISO.dayOfWeek(), 1)
                                                .toFormatter();
            
            LocalDateTime ldt=LocalDate.parse(cw, startOfWeekFormat)
                                .atStartOfDay()
                                .with(TemporalAdjusters.next(DayOfWeek.MONDAY));
            System.out.println(ldt);
        }
    }
    

    Output:

    2019-09-02T00:00