Java - How to calculate the first and last day of each week

前端 未结 11 981
难免孤独
难免孤独 2020-12-05 05:16

I\'m trying to create a weekly calendar that looks like this: http://dhtmlx.com/docs/products/dhtmlxScheduler/sample_basic.html

How can I calculate every week date?

11条回答
  •  一生所求
    2020-12-05 06:01

    With the new date and time API in Java 8 you would do:

    LocalDate now = LocalDate.now();
    
    // determine country (Locale) specific first day of current week
    DayOfWeek firstDayOfWeek = WeekFields.of(Locale.getDefault()).getFirstDayOfWeek();
    LocalDate startOfCurrentWeek = now.with(TemporalAdjusters.previousOrSame(firstDayOfWeek));
    
    // determine last day of current week
    DayOfWeek lastDayOfWeek = firstDayOfWeek.plus(6); // or minus(1)
    LocalDate endOfWeek = now.with(TemporalAdjusters.nextOrSame(lastDayOfWeek));
    
    // Print the dates of the current week
    LocalDate printDate = startOfCurrentWeek;
    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("EEE dd/MM/yyyy");
    for (int i=0; i < 7; i++) {
        System.out.println(printDate.format(formatter));
        printDate = printDate.plusDays(1);
    }
    

提交回复
热议问题