Java-如何使用Joda Time Jar计算准确的时差

前端之家收集整理的这篇文章主要介绍了Java-如何使用Joda Time Jar计算准确的时差前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我从 http://sourceforge.net/projects/joda-time/files/joda-time/2.2/下载的Joda时间罐有问题.当我使用以下代码段时,我可以得到结果
static void timeDifferencewithJoda()  {

    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.

但我面对这个时差的冲突.

01/14/2012 09:29:58

01/15/2012 10:31:48

这两个时间已经宣布,但没有迹象表明像AM或PM这样的时期.即,时间可能是早上或晚上.我如何得到确切的时差?

任何有关这方面的帮助都会很有用.

解决方法

使用 Joda formatter(非AM / PM)
final String dateStart = "01/14/2012 09:29:58";
  final String dateStop = "01/15/2012 10:31:48";
  final DateTimeFormatter format = DateTimeFormat.forPattern("MM/dd/yyyy HH:mm:ss");
  final DateTime dt1 = format.parseDateTime(dateStart);
  final DateTime dt2 = format.parseDateTime(dateStop);

  System.out.print(Days.daysBetween(dt1,");
  System.out.print(Hours.hoursBetween(dt1,");
  System.out.print(Minutes.minutesBetween(dt1,");
  System.out.print(Seconds.secondsBetween(dt1,dt2).getSeconds() % 60 + " seconds.");

使用Joda formatter(带AM / PM)

final String dateStart = "01/14/2012 09:29:58 AM";
  final String dateStop = "01/15/2012 10:31:48 PM";
  final DateTimeFormatter format = DateTimeFormat.forPattern("MM/dd/yyyy hh:mm:ss a");
  final DateTime dt1 = format.parseDateTime(dateStart);
  final DateTime dt2 = format.parseDateTime(dateStop);

  System.out.print(Days.daysBetween(dt1,dt2).getSeconds() % 60 + " seconds.");

Period计算单位

final Period period = new Period(dt1,dt2);
  System.out.print(period.getDays() + " days,");
  System.out.print(period.getHours() + " hours,");
  System.out.print(period.getMinutes() + " minutes,");
  System.out.print(period.getSeconds() + " seconds.");
原文链接:https://www.f2er.com/java/124139.html

猜你在找的Java相关文章