如何获取java.util.Date中当前季度的第一个日期和最后一个日期 [英] How to get the first date and last date of current quarter in java.util.Date
问题描述
我需要将当前季度的第一个日期作为java.util.Date对象,并将当前季度的最后日期作为java.util获取。日期对象。
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?
假设Q1 = Jan Feb Mar,Q2 = Apr,May,Jun等。
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();
}
这应该工作,但我建议你比我做的更仔细地测试:)
注意:Java中的int值的分割返回底层值。
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.
这篇关于如何获取java.util.Date中当前季度的第一个日期和最后一个日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!