获取日期差值

public class CalendarTest {
	/**
	 * 获取日期差值
	 * @param sdate1 起始日期
	 * @param sdate2 结束日期
	 * @param fmt 日期格式
	 * @param tz 时区
	 * @param 差值类型(1:天,2:周,3:月,4:年,5:小时)
	 * */
	public static int getDateDiff(String sdate1,String sdate2,String fmt,TimeZone tz,int type) {
			SimpleDateFormat df = new SimpleDateFormat(fmt);

			Date date1 = null;
			Date date2 = null;

			try {
				date1 = df.parse(sdate1);
				date2 = df.parse(sdate2);
			} catch (ParseException pe) {
				pe.printStackTrace();
			}

			Calendar cal1 = null;
			Calendar cal2 = null;

			if (tz == null) {
				cal1 = Calendar.getInstance();
				cal2 = Calendar.getInstance();
			} else {
				cal1 = Calendar.getInstance(tz);
				cal2 = Calendar.getInstance(tz);
			}

			// different date might have different offset
			cal1.setTime(date1);
			long ldate1 =
				date1.getTime()
					+ cal1.get(Calendar.ZONE_OFFSET)
					+ cal1.get(Calendar.DST_OFFSET);

			cal2.setTime(date2);
			long ldate2 =
				date2.getTime()
					+ cal2.get(Calendar.ZONE_OFFSET)
					+ cal2.get(Calendar.DST_OFFSET);

			// Use integer calculation, truncate the decimals
			int hr1 = (int) (ldate1 / 3600000); //60*60*1000
			int hr2 = (int) (ldate2 / 3600000);

			int days1 = (int) hr1 / 24;
			int days2 = (int) hr2 / 24;

			int hourDiff = hr2 - hr1;
			int dateDiff = days2 - days1;
			int weekOffset =
				(cal2.get(Calendar.DAY_OF_WEEK)
					- cal1.get(Calendar.DAY_OF_WEEK))
					< 0
					? 1
					: 0;
			int weekDiff = dateDiff / 7 + weekOffset;
			int yearDiff = cal2.get(Calendar.YEAR) - cal1.get(Calendar.YEAR);
			int monthDiff =
				yearDiff * 12
					+ cal2.get(Calendar.MONTH)
					- cal1.get(Calendar.MONTH);

			switch (type) {
				case 1 :
					return dateDiff;
				case 2 :
					return weekDiff;
				case 3 :
					return monthDiff;
				case 4 :
					return yearDiff;
				case 5 :
					return hourDiff;
				default :
					return 0;
			}
	}
	
	public static void main(String[] args){
		System.out.println(getDateDiff("2010-03-22","2011-03-27","yyyy-MM-dd",null,1));
	}
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值