發現JAVA竟沒有如此好用的API,
只好由自己模擬一個來使用,
我將日期差距和時間差分作兩個function,
請注意日期的部分,
若是2012/12/20和2013/01/01相減的話,
以 y 輸入會回傳 1,M輸入傳回 1 ,d 輸入傳回12
public int dateDiff(String type,String d1,String d2){
/*
* 比較兩日期間的差異 回傳差異值
*
* type格式 : d M y
* 天 月 年
*
* d1,d2為兩個時間,只回傳差異,不分正負值
*/
Date date1 = null,date2=null;
Calendar c1=Calendar.getInstance();
Calendar c2=Calendar.getInstance();
int y,m,d;
//可接受的日期格式 可自行新增
String[] dateStyle={"yyyy/MM/dd","yyyy-MM-dd","yyyy MM dd"};
//轉換日期格式
for(String style:dateStyle){
DateFormat smf=new SimpleDateFormat(style);
smf.setLenient(false);
try{
date1=smf.parse(d1);
date2=smf.parse(d2);
break;
}
catch(Exception e){
}
}
c1.setTime(date1);
c2.setTime(date2);
y=Math.abs(c1.get(Calendar.YEAR)-c2.get(Calendar.YEAR));
m=Math.abs(c1.get(Calendar.YEAR)*12+c1.get(Calendar.MONTH)-c2.get(Calendar.YEAR)*12+c2.get(Calendar.MONTH));
d=(int)((Math.abs(c1.getTimeInMillis()-c2.getTimeInMillis()))/(1000*60*60*24));
y=y>0?y:0;
m=m>0?m:0;
if(type.equals("d")){
return d;
}
else if(type.equals("M")){
return m;
}
else if(type.equals("y")){
return y;
}else{
System.err.println("輸入錯誤 type = "+type);
}
return 0;
}
以下為時間差距的function,處理方式很簡易,算出毫秒再分別計算秒、分、時,
public long timeDiff(String type,String t1,String t2){
/*
* 比較兩時間的差異 回傳差異值
*
* type格式 : s m H
* 秒 分 時
*
* t1,t2為兩個時間,只回傳差異,不分正負值
*/
//時間格式 注意HH為24小時制
String[] timeStyle={"HH:mm:ss"};
Date time1=null,time2=null;
for(String style:timeStyle){
DateFormat smf=new SimpleDateFormat(style);
smf.setLenient(false);
try{
time1=smf.parse(t1);
time2=smf.parse(t2);
break;
}
catch(Exception e){
}
}
Long timeDiff=Math.abs(time1.getTime()-time2.getTime());
if(type.equals("s")){
return timeDiff/1000;
}
else if(type.equals("m")){
return timeDiff/(1000*60);
}
else if(type.equals("H")){
return timeDiff/(1000*60*60);
}
else{
System.err.println("type格式錯誤 "+type);
}
return 0;
}
沒有留言:
張貼留言