下面程序使用了两种方法计算两个时间相差 天,小时,分钟,秒
可以看看,两种写法的优缺点。
1 package jodotest; 2 3 import java.text.ParseException; 4 import java.text.SimpleDateFormat; 5 import java.util.Date; 6 7 import org.joda.time.DateTime; 8 import org.joda.time.Days; 9 import org.joda.time.Hours; 10 import org.joda.time.Interval; 11 import org.joda.time.Minutes; 12 import org.joda.time.Period; 13 import org.joda.time.Seconds; 14 15 /** 16 * @author wanggang 17 * 18 */ 19 public class Test { 20 public static void test1(Date d1, Date d2){ 21 22 // 毫秒ms 23 long diff = d2.getTime() - d1.getTime(); 24 25 long diffSeconds = diff / 1000 % 60; 26 long diffMinutes = diff / (60 * 1000) % 60; 27 long diffHours = diff / (60 * 60 * 1000) % 24; 28 long diffDays = diff / (24 * 60 * 60 * 1000); 29 30 System.out.print("时间相差:"); 31 System.out.print(diffDays + " 天 "); 32 System.out.print(diffHours + " 小时 "); 33 System.out.print(diffMinutes + " 分钟 "); 34 System.out.print(diffSeconds + " 秒."); 35 System.out.println(); 36 } 37 38 public static void test2(Date d1, Date d2) throws ParseException{ 39 40 DateTime dt1 = new DateTime(d1); 41 DateTime dt2 = new DateTime(d2); 42 System.out.print("时间相差:"); 43 System.out.print(Days.daysBetween(dt1, dt2).getDays() + " 天 "); 44 System.out.print(Hours.hoursBetween(dt1, dt2).getHours() % 24 + " 小时 "); 45 System.out.print(Minutes.minutesBetween(dt1, dt2).getMinutes() % 60 + " 分钟 "); 46 System.out.print(Seconds.secondsBetween(dt1, dt2).getSeconds() % 60+ " 秒."); 47 System.out.println(); 48 } 49 50 public static void test3(Date d1, Date d2){ 51 Interval interval = new Interval(d1.getTime(), d2.getTime()); 52 Period p = interval.toPeriod(); 53 System.out.println("时间相差:"+p.getDays()+" 天 " + p.getHours()+ " 小时 "+p.getMinutes()+" 分钟"+p.getSeconds()+" 秒"); 54 } 55 56 57 58 59 /** 60 * @param args 61 * @throws ParseException 62 */ 63 public static void main(String[] args) throws ParseException { 64 String dateStart = "2013-08-13 16:29:58"; 65 String dateStop = "2013-08-13 16:31:48"; 66 67 SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); 68 69 Date d1 = format.parse(dateStart); 70 Date d2 = format.parse(dateStop); 71 test1(d1, d2); 72 test2(d1, d2); 73 test3(d1, d2); 74 } 75 }
程序输出:
时间相差:0 天 0 小时 1 分钟 50 秒.
时间相差:0 天 0 小时 1 分钟 50 秒.
时间相差:0 天 0 小时 1 分钟50 秒