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