java - to get the start date and end date of each week for the given month

前端 未结 3 607
暗喜
暗喜 2021-01-06 12:03

Following is the code that I am using to calculate the week start date and end date for the given month. Assume week start day is MONDAY and week end day is SUNDAY. For exa

3条回答
  •  挽巷
    挽巷 (楼主)
    2021-01-06 12:30

    You are using terrible date-time classes that were supplanted years ago by the modern java.time classes defined in JSR 310. This work is much easier now.

    YearMonth

    The YearMonth class represents a specific month as a whole. Specify the month using the Month enum.

    YearMonth ym = YearMonth.of( 2013 , Month.JANUARY ) ;
    

    LocalDate

    Get the first of the month.

    LocalDate firstOfMonth = ym.atDay( 1 ) ;
    

    TemporalAdjuster

    Get the previous Monday, or stay with this date if it is a Monday.

    TemporalAdjuster ta = TemporalAdjusters.previousOrSame( DayOfWeek.MONDAY ) ;
    LocalDate previousOrSameMonday = firstOfMonth.with( ta ) ;
    

    Then loop a week at a time.

    LocalDate endOfMonth = ym.atEndOfMonth() ;
    LocalDate weekStart = previousOrSameMonday ; 
    do {
        LocalDate weekStop = weekStart.plusDays( 6 ) ;
        System.out.println( "Week: " + weekStart + " to " + weekStop ) ;
        // Set up the next loop.
        weekStart = weekStart.plusWeeks( 1 ) ;
    } while ( ! weekStart.isAfter( endOfMonth ) ) ;
    

    See this code run live at IdeOne.com.

    Week: Monday, December 31, 2012 to Sunday, January 6, 2013

    Week: Monday, January 7, 2013 to Sunday, January 13, 2013

    Week: Monday, January 14, 2013 to Sunday, January 20, 2013

    Week: Monday, January 21, 2013 to Sunday, January 27, 2013

    Week: Monday, January 28, 2013 to Sunday, February 3, 2013

    By the way, you might want to learn about, and consider using, the ISO 860 standard definition of a week. And then use the YearWeek class of the ThreeTen-Extra library.

提交回复
热议问题