计算两个日期时间之间的月数

/**
	 * 计算两个日期之间的月数
	 * @param time1 时间
	 * @param time2 时间
	 * @return
	 * @throws ParseException
	 * @author sg/2014-6-26/上午10:09:01
	 */
	public static int getMonthSpace(Timestamp time1, Timestamp time2)
			throws ParseException {
		int result = 0;
		Date date1 = new Date();
		Date date2 = new Date();
		
		if(time1.before(time2)){
			date1 = time1;
			date2 = time2;
		}else if(time1.after(time2)){
			date1 = time2;
			date2 = time1;
		}
		
		Calendar c1 = Calendar.getInstance();
		Calendar c2 = Calendar.getInstance();
		c1.setTime(date1);
		c2.setTime(date2);
		result = (c2.get(Calendar.YEAR) - c1.get(Calendar.YEAR))*12+(c2.get(Calendar.MONTH) - c1.get(Calendar.MONTH));
		int dayMonths = c2.get(Calendar.DAY_OF_MONTH)-c1.get(Calendar.DAY_OF_MONTH);
		if(dayMonths<0){
			result--;
		}else if(dayMonths>0){
			result ++;
		}else{//日期相同,时间不同情况
			int hourDays = c2.get(Calendar.HOUR_OF_DAY)-c1.get(Calendar.HOUR_OF_DAY);
			if(hourDays>0){//判断小时
				result++;
			}else if(hourDays==0){//判断分钟
				int minHours = c2.get(Calendar.MINUTE)-c1.get(Calendar.MINUTE);
				if(minHours>0){
					result++;
				}else if(minHours==0){//判断秒
					int secMins = c2.get(Calendar.SECOND)-c1.get(Calendar.SECOND);
					if(secMins>0){
						result++;
					}else if(secMins==0){//判断毫秒
						int millSecs = c2.get(Calendar.MILLISECOND )-c1.get(Calendar.MILLISECOND );
						if(millSecs>0){
							result++;
						}
					}
				}
			}
		}
		return result == 0 ? 1 : Math.abs(result);
	}



转载于:https://my.oschina.net/guying/blog/284304

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值