知识大全 Java计算日期和时间差

Posted 时间差

篇首语:男儿欲遂平生志,五经勤向窗前读。本文由小常识网(cha138.com)小编为大家整理,主要介绍了知识大全 Java计算日期和时间差相关的知识,希望对你有一定的参考价值。

Java计算日期和时间差  以下文字资料是由(全榜网网www.cha138.com)小编为大家搜集整理后发布的内容,让我们赶快一起来看一下吧!

  这篇文章将使用两个例子计算两个日期的时间差

   使用Java SDK

   使用Joda库

   使用Java SDK

  计算两个Date之间的时间差 基本思路为把Date转换为ms(微秒) 然后计算两个微秒时间差 时间的兑换规则如下

   s秒 = ms毫秒 min分种 = s秒 hours小时 = min分钟 day天 = hours小时

  package qiyadeng date;

  import java text SimpleDateFormat;

  import java util Date;

  public class DateDifferentExample

  public static void main(String[] args)

  String dateStart = : : ;

  String dateStop = : : ;

  SimpleDateFormat format = new SimpleDateFormat( yyyy MM dd HH:mm:ss );

  Date d = null;

  Date d = null;

  try

  d = format parse(dateStart);

  d = format parse(dateStop);

  //毫秒ms

  long diff = d getTime() d getTime();

  long diffSeconds = diff / % ;

  long diffMinutes = diff / ( * ) % ;

  long diffHours = diff / ( * * ) % ;

  long diffDays = diff / ( * * * );

  System out print( 两个时间相差 );

  System out print(diffDays + 天 );

  System out print(diffHours + 小时 );

  System out print(diffMinutes + 分钟 );

  System out print(diffSeconds + 秒 );

   catch (Exception e)

  e printStackTrace();

  

  

  

  运行结果

  两个时间相差 天 小时 分钟 秒

   Joda时间库

  package qiyadeng date;

  import java text SimpleDateFormat;

  import java util Date;

  import joda time DateTime;

  import joda time Days;

  import joda time Hours;

  import joda time Minutes;

  import joda time Seconds;

  public class JodaDateDifferentExample

  public static void main(String[] args)

  String dateStart = : : ;

  String dateStop = : : ;

  SimpleDateFormat format = new SimpleDateFormat( yyyy MM dd HH:mm:ss );

  Date d = null;

  Date d = null;

  try

  d = format parse(dateStart);

  d = format parse(dateStop);

  DateTime dt = new DateTime(d );

  DateTime dt = new DateTime(d );

  System out print( 两个时间相差 );

  System out print(Days daysBeeen(dt dt ) getDays() + 天 );

  System out print(Hours hoursBeeen(dt dt ) getHours() %

  + 小时 );

  System out print(Minutes minutesBeeen(dt dt ) getMinutes() %

  + 分钟 );

  System out print(Seconds secondsBeeen(dt dt ) getSeconds() %

  + 秒 );

   catch (Exception e)

  e printStackTrace();

  

  

  

  运行结果

cha138/Article/program/Java/hx/201311/26928

相关参考