How to get the first date and last date of current quarter in java.util.Date

前端 未结 8 852

I need to get the first date of the current quarter as a java.util.Date object and the last date of the current quarter as a java.util.Date

8条回答
  •  旧巷少年郎
    2020-12-10 15:11

    Keep it simple

    I think the following is most elegant because it doesn't have any magical numbers (like 92), TemporalAdjusters or non-obvious calculations, and can easily be adapted to get the start and end of any quarter (not just current quarter).

    import static java.time.temporal.IsoFields.QUARTER_OF_YEAR;
    
    LocalDate date = LocalDate.now(); // can be any other date
    
    int year = date.getYear();
    int quarter = date.get(QUARTER_OF_YEAR);
            
    LocalDate start = YearMonth.of(year, 1)                    // January of given year
                               .with(QUARTER_OF_YEAR, quarter) // becomes first month of given quarter
                               .atDay(1);                      // becomes first day of given quarter
    
    LocalDate end = YearMonth.of(year, 3)                      // March of given year
                             .with(QUARTER_OF_YEAR, quarter)   // becomes 3rd (last) month of given quarter
                             .atEndOfMonth();                  // becomes last day of given quarter
    

    If you don't have a date, but just a year and quarter (e.g. Q2 2020), this becomes:

    LocalDate start = YearMonth.of(2020, 1).with(QUARTER_OF_YEAR, 2).atDay(1);
    LocalDate end = YearMonth.of(2020, 3).with(QUARTER_OF_YEAR, 2).atEndOfMonth();
    

提交回复
热议问题