java获取季度,如何获取java.util.Date中当前季度的第一个日期和最后一个日期

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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值