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

date, java

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 object.

I'm using following methods to get this month first date and this month last date.

private   Date getThisMonthFirstDate(){    Calendar calendar = new GregorianCalendar();    calendar.set(Calendar.HOUR_OF_DAY, 0);    calendar.set(Calendar.MINUTE, 0);    calendar.set(Calendar.SECOND, 0);    calendar.set(Calendar.MILLISECOND, 0);    calendar.set(Calendar.DAY_OF_MONTH, 1);    return calendar.getTime();}private   Date getThisMonthLastDate(){    Calendar calandar = new GregorianCalendar();    calendar.set(Calendar.HOUR_OF_DAY, 0);    calendar.set(Calendar.MINUTE, 0);    calendar.set(Calendar.SECOND, 0);    calendar.set(Calendar.MILLISECOND, 0);    calendar.set(Calendar.DAY_OF_MONTH,1);    calendar.add(Calendar.MONTH, 1);    calendar.add(Calendar.DATE, -1);   return calendar.getTime();}

Is there a way to modify that function to achieve this or could anyone point out a better way?

Assume that Q1 = Jan Feb Mar, Q2 = Apr, May, Jun, etc.

Best Solution

Pure Java-8+ solution:

LocalDate localDate = LocalDate.now();LocalDate firstDayOfQuarter = localDate.with(localDate.getMonth().firstMonthOfQuarter())    .with(TemporalAdjusters.firstDayOfMonth());LocalDate lastDayOfQuarter = firstDayOfQuarter.plusMonths(2)    .with(TemporalAdjusters.lastDayOfMonth());