這篇文章將使用兩個例子計算兩個日期的時間差。
1.使用Java SDK。
2.使用Joda庫。
1.使用Java SDK
計算兩個Date之間的時間差,基本思路為把Date轉換為ms(微秒),然後計算兩個微秒時間差。時間的兌換規則如下:
1s秒 = 1000ms毫秒 1min分種 = 60s秒 1hours小時 = 60min分鐘 1day天 = 24hours小時
package com.qiyadeng.date; import java.text.SimpleDateFormat; import java.util.Date; public class DateDifferentExample { public static void main(String[] args) { String dateStart = "2013-02-19 09:29:58"; String dateStop = "2013-02-20 11:31:48"; SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); Date d1 = null; Date d2 = null; try { d1 = format.parse(dateStart); d2 = format.parse(dateStop); //毫秒ms long diff = d2.getTime() - d1.getTime(); long diffSeconds = diff / 1000 % 60; long diffMinutes = diff / (60 * 1000) % 60; long diffHours = diff / (60 * 60 * 1000) % 24; long diffDays = diff / (24 * 60 * 60 * 1000); System.out.print("兩個時間相差:"); System.out.print(diffDays + " 天, "); System.out.print(diffHours + " 小時, "); System.out.print(diffMinutes + " 分鐘, "); System.out.print(diffSeconds + " 秒."); } catch (Exception e) { e.printStackTrace(); } } }
運行結果:
兩個時間相差:1 天, 2 小時, 1 分鐘, 50 秒.
2.Joda時間庫
package com.qiyadeng.date; import java.text.SimpleDateFormat; import java.util.Date; import org.joda.time.DateTime; import org.joda.time.Days; import org.joda.time.Hours; import org.joda.time.Minutes; import org.joda.time.Seconds; public class JodaDateDifferentExample { public static void main(String[] args) { String dateStart = "2013-02-19 09:29:58"; String dateStop = "2013-02-20 11:31:48"; SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); Date d1 = null; Date d2 = null; try { d1 = format.parse(dateStart); d2 = format.parse(dateStop); DateTime dt1 = new DateTime(d1); DateTime dt2 = new DateTime(d2); System.out.print("兩個時間相差:"); System.out.print(Days.daysBetween(dt1, dt2).getDays() + " 天, "); System.out.print(Hours.hoursBetween(dt1, dt2).getHours() % 24 + " 小時, "); System.out.print(Minutes.minutesBetween(dt1, dt2).getMinutes() % 60 + " 分鐘, "); System.out.print(Seconds.secondsBetween(dt1, dt2).getSeconds() % 60 + " 秒."); } catch (Exception e) { e.printStackTrace(); } } }
運行結果:
兩個時間相差:1 天, 2 小時, 1 分鐘, 50 秒.
出處:http://www.qiyadeng.com/