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));
}
}