public static void main(String[] args) {
// TODO Auto-generated method stub
try {
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//設置日期格式
String currentTime = df.format(new Date());// new Date()爲獲取當前系統時間
String oldTime = "2013-12-29 12:13:22";// 之前查詢的時間
String aString = TimeDiff(oldTime, currentTime);
System.out.println(aString);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static String TimeDiff(String oldTime, String newTime)
throws Exception {
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
Long beginL = format.parse(oldTime).getTime();
Long endL = format.parse(newTime).getTime();
Long year = (endL - beginL) / 86400000 / 30 / 12;
Long month = (endL - beginL) / 86400000 / 30;
Long day = (endL - beginL) / 86400000;
Long hour = ((endL - beginL) % 86400000) / 3600000;
Long min = ((endL - beginL) % 86400000 % 3600000) / 60000;
if(year == 0){
if(month == 0){
if(day == 0){
if(hour == 0){
if(min > 0){
return min+"分鐘前";
}else{
return "剛剛";
}
}else{
return hour+"小時前";
}
}else{
return day+"天前";
}
}else{
return month+"個月前";
}
}else{
return year+"年前";
}
}
時間差 dateDifference
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.