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
Using the answer from Volodymyr Masliy using java.util.Date, there is some bug that came up in my tests
If you enter "31/05/2000" it returns July 1st of that year, which is obviously not what we're looking for.
I used java.time.LocalDate as suggested by Basil Bourque and dheeran and the test case works ok.
My method is as follows:
public static Date lastDayOfQuarter(Date date) {
LocalDate inputDate = date.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
LocalDate lastDayOfQuarter = inputDate.withMonth(inputDate.get(IsoFields.QUARTER_OF_YEAR) * 3).with(TemporalAdjusters.lastDayOfMonth());
return Date.from(LastDayOfQuarter.atStartOfDay().atZone(ZoneId.systemDefault()).toInstant());
}
My UnitTests using ZohhakRunner are as follows:
@TestWith({
"01/03/2000, 31/03/2000",
"05/04/1982, 30/06/1982",
"31/05/1982, 30/06/1982",
"09/07/1990, 30/09/1990",
"11/11/2019, 31/12/2019",
"31/03/2016, 31/03/2016"})
public void lastDayOfQuarter_useInputDate_returnExpectedEndOfQuarterDate(String inputDateAsString, String endOfQuarterAsString) throws ParseException{
Date inputDate = new SimpleDateFormat("dd/MM/yyyy").parse(inputDateAsString);
Date expectedDate = new SimpleDateFormat("dd/MM/yyyy").parse(endOfQuarterAsString);
Date result = DateUtils.lastDayOfQuarter(inputDate);
assertEquals(result, expectedDate);
}