calendar java 当前时间_使用java的Calendar对象获得当前日期

思路:

先获得当前季度的开始和结束日期,在当前日期的基础上往前推3个月即上个季度的开始和结束日期

/**

* @param flag true:开始日期;false:结束日期

* @return

*/

public static String getLastQuarterTime(boolean flag){

SimpleDateFormat shortSdf = new SimpleDateFormat("yyyy-MM-dd");

SimpleDateFormat longSdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

String resultDate="";

Date now = null;

try {

Calendar calendar = Calendar.getInstance();

int currentMonth = calendar.get(Calendar.MONTH) + 1;

//true:开始日期;false:结束日期

if(flag){

if (currentMonth >= 1 && currentMonth <= 3)

calendar.set(Calendar.MONTH, 0);

else if (currentMonth >= 4 && currentMonth <= 6)

calendar.set(Calendar.MONTH, 3);

else if (currentMonth >= 7 && currentMonth <= 9)

calendar.set(Calendar.MONTH, 6);

else if (currentMonth >= 10 && currentMonth <= 12)

calendar.set(Calendar.MONTH, 9);

calendar.set(Calendar.DATE, 1);

now = longSdf.parse(shortSdf.format(calendar.getTime()) + " 00:00:00");

}else{

if (currentMonth >= 1 && currentMonth <= 3) {

calendar.set(Calendar.MONTH, 2);

calendar.set(Calendar.DATE, 31);

} else if (currentMonth >= 4 && currentMonth <= 6) {

calendar.set(Calendar.MONTH, 5);

calendar.set(Calendar.DATE, 30);

} else if (currentMonth >= 7 && currentMonth <= 9) {

calendar.set(Calendar.MONTH, 8);

calendar.set(Calendar.DATE, 30);

} else if (currentMonth >= 10 && currentMonth <= 12) {

calendar.set(Calendar.MONTH, 11);

calendar.set(Calendar.DATE, 31);

}

now = longSdf.parse(shortSdf.format(calendar.getTime()) + " 23:59:59");

}

calendar.setTime(now);// 设置日期

calendar.add(Calendar.MONTH, -3);

resultDate = longSdf.format(calendar.getTime());

} catch (Exception e) {

;

}

return resultDate;

}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值