熱點推薦:
您现在的位置: 電腦知識網 >> 編程 >> Java編程 >> Java核心技術 >> 正文

Java計算日期和時間差

2013-11-23 19:28:35  來源: Java核心技術 

  這篇文章將使用兩個例子計算兩個日期的時間差

  使用Java SDK

  使用Joda庫

  使用Java SDK

  計算兩個Date之間的時間差基本思路為把Date轉換為ms(微秒)然後計算兩個微秒時間差時間的兌換規則如下

  s秒 = ms毫秒 min分種 = s秒 hours小時 = min分鐘 day天 = hours小時

  package comqiyadengdate;

  import javatextSimpleDateFormat;

  import javautilDate;

  public class DateDifferentExample {

  public static void main(String[] args) {

  String dateStart = ::;

  String dateStop = ::;

  SimpleDateFormat format = new SimpleDateFormat(yyyyMMdd HH:mm:ss);

  Date d = null;

  Date d = null;

  try {

  d = formatparse(dateStart);

  d = formatparse(dateStop);

  //毫秒ms

  long diff = dgetTime() dgetTime();

  long diffSeconds = diff / % ;

  long diffMinutes = diff / ( * ) % ;

  long diffHours = diff / ( * * ) % ;

  long diffDays = diff / ( * * * );

  Systemoutprint(兩個時間相差);

  Systemoutprint(diffDays + );

  Systemoutprint(diffHours + 小時 );

  Systemoutprint(diffMinutes + 分鐘 );

  Systemoutprint(diffSeconds + );

  } catch (Exception e) {

  eprintStackTrace();

  }

  }

  }

  運行結果

  兩個時間相差 小時 分鐘

  Joda時間庫

  package comqiyadengdate;

  import javatextSimpleDateFormat;

  import javautilDate;

  import orgjodatimeDateTime;

  import orgjodatimeDays;

  import orgjodatimeHours;

  import orgjodatimeMinutes;

  import orgjodatimeSeconds;

  public class JodaDateDifferentExample {

  public static void main(String[] args) {

  String dateStart = ::;

  String dateStop = ::;

  SimpleDateFormat format = new SimpleDateFormat(yyyyMMdd HH:mm:ss);

  Date d = null;

  Date d = null;

  try {

  d = formatparse(dateStart);

  d = formatparse(dateStop);

  DateTime dt = new DateTime(d);

  DateTime dt = new DateTime(d);

  Systemoutprint(兩個時間相差);

  Systemoutprint(DaysdaysBetween(dt dt)getDays() + );

  Systemoutprint(HourshoursBetween(dt dt)getHours() %

  + 小時 );

  Systemoutprint(MinutesminutesBetween(dt dt)getMinutes() %

  + 分鐘 );

  Systemoutprint(SecondssecondsBetween(dt dt)getSeconds() %

  + );

  } catch (Exception e) {

  eprintStackTrace();

  }

  }

  }

  運行結果

  兩個時間相差 小時 分鐘


From:http://tw.wingwit.com/Article/program/Java/hx/201311/26928.html
    Copyright © 2005-2013 電腦知識網 Computer Knowledge   All rights reserved.