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

时间:2013-07-06 05:27:05

标签: java datetime jodatime

我从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这样的时期。即,时间可能是早上或晚上。我如何得到确切的时差?

对此有任何帮助都很有用。

2 个答案:

答案 0 :(得分:12)

使用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, 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.");    

使用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).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.");  

使用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.");

答案 1 :(得分:0)

在您的SimpleDateFormat中,您有HH指定小时数,并且如文档中所述,HH代表 - 白天小时(0-23)。因此AM / PM不适用于此处。如果您想要AM / PM小时,则应使用KK或hh代替。您可以查看文档here