java计算时间差的几种方法
By:Roy.LiuLast updated:2013-02-19
用JAVA计算日期,时间差的几种方法
1. 手工计算
2.采用一个三方的jar包(Joda time library)
3. 利用TimeUnit类(java.util.concurrent 包中)
方法一:手工计算
结果为:
方法二:采用 joda-time-2.1.jar (这里去下载:http://joda-time.sourceforge.net/)
结果:
方法三: 采用TimeUnit ( java.util.concurrent包中的TimeUnit)
1. 手工计算
2.采用一个三方的jar包(Joda time library)
3. 利用TimeUnit类(java.util.concurrent 包中)
方法一:手工计算
import java.text.SimpleDateFormat; import java.util.Date; public class DateDifferentExample { public static void main(String[] args) { String dateStart = "01/14/2012 09:29:58"; String dateStop = "01/15/2012 10:31:48"; //HH converts hour in 24 hours format (0-23), day calculation SimpleDateFormat format = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss"); Date d1 = null; Date d2 = null; try { d1 = format.parse(dateStart); d2 = format.parse(dateStop); //in milliseconds 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(diffDays + " days, "); System.out.print(diffHours + " hours, "); System.out.print(diffMinutes + " minutes, "); System.out.print(diffSeconds + " seconds."); } catch (Exception e) { e.printStackTrace(); } } }
结果为:
1 days, 1 hours, 1 minutes, 50 seconds.
方法二:采用 joda-time-2.1.jar (这里去下载:http://joda-time.sourceforge.net/)
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 = "01/14/2012 09:29:58"; String dateStop = "01/15/2012 10:31:48"; SimpleDateFormat format = new SimpleDateFormat("MM/dd/yyyy 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(Days.daysBetween(dt1, dt2).getDays() + " days, "); System.out.print(Hours.hoursBetween(dt1, dt2).getHours() % 24 + " hours, "); System.out.print(Minutes.minutesBetween(dt1, dt2).getMinutes() % 60 + " minutes, "); System.out.print(Seconds.secondsBetween(dt1, dt2).getSeconds() % 60 + " seconds."); } catch (Exception e) { e.printStackTrace(); } } }
结果:
1 days, 1 hours, 1 minutes, 50 seconds.
方法三: 采用TimeUnit ( java.util.concurrent包中的TimeUnit)
long diffSeconds = diff / 1000 % 60; long diffMinutes = diff / (60 * 1000) % 60;
long diffSeconds = TimeUnit.MILLISECONDS.toSeconds(diff) % 60; long diffMinutes = TimeUnit.MILLISECONDS.toMinutes(diff) % 60; long diffHours = TimeUnit.MILLISECONDS.toHours(diff) % 24; long diffDays = TimeUnit.MILLISECONDS.toDays(diff);
From:一号门
COMMENTS