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

前端 未结 8 851

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:14
    private static Date getFirstDayOfQuarter(Date date) {
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        cal.set(Calendar.DAY_OF_MONTH, 1);
        cal.set(Calendar.MONTH, cal.get(Calendar.MONTH)/3 * 3);
        return cal.getTime();
    }
    
    private static Date getLastDayOfQuarter(Date date) {
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        cal.set(Calendar.DAY_OF_MONTH, 1);
        cal.set(Calendar.MONTH, cal.get(Calendar.MONTH)/3 * 3 + 2);
        cal.set(Calendar.DAY_OF_MONTH, cal.getActualMaximum(Calendar.DAY_OF_MONTH));
        return cal.getTime();
    }
    

    This should work, but I suggest you to test it more carefully than I did. Note: Division of int values in Java returns the floor value.

    0 讨论(0)
  • 2020-12-10 15:17

    It's pretty simple with LocalDate

    LocalDate inputDate = LocalDate.parse("2018-09-04");
    LocalDate firstDayOfQuarter = inputDate.withMonth(inputDate.get(IsoFields.QUARTER_OF_YEAR) * 3 - 2).with(TemporalAdjusters.firstDayOfMonth());
    LocalDate lastDayOfQuarter = inputDate.withMonth(inputDate.get(IsoFields.QUARTER_OF_YEAR) * 3).with(TemporalAdjusters.lastDayOfMonth());
    

    Cheers!

    0 讨论(0)
提交回复
热议问题