Joda-Time DateTimes之间的双重类型秒

时间:2013-11-19 15:35:46

标签: jodatime

我可以使用Seconds类获得两个DateTime之间的整数秒:

Seconds.secondsBetween(now, dateTime);

但是,我不清楚Joda-Time API如何让我得到小数秒的差异,即秒为双倍?我需要从毫秒或刻度计算小数秒吗? API通常是如此优雅和富有表现力,我觉得我可能会遗漏某些东西......

1 个答案:

答案 0 :(得分:1)

不太难......使用Interval 2.3。

中的Joda-Time课程

Java 7中的示例代码......

// © 2013 Basil Bourque. This source code may be used freely forever by anyone taking full responsibility for doing so.

// A good practice is to specify your time zone rather than rely on default.
org.joda.time.DateTimeZone californiaTimeZone = org.joda.time.DateTimeZone.forID("America/Los_Angeles");

// Now.
org.joda.time.DateTime now = new org.joda.time.DateTime(californiaTimeZone);

// Wait a moment.
try {
    java.util.concurrent.TimeUnit.MILLISECONDS.sleep(3500);
} catch (InterruptedException e) {
    e.printStackTrace();
}

// Later.
org.joda.time.DateTime aMomentLater = new org.joda.time.DateTime(californiaTimeZone);

// Elapsed.
org.joda.time.Interval interval = new org.joda.time.Interval( now, aMomentLater );
long milliseconds = interval.toDurationMillis();
double seconds = ( (double)milliseconds / 1000 );

// Display
System.out.println( "Elapsed: " + seconds + " seconds.  ( " + milliseconds + " milliseconds )");

跑步时......

Elapsed: 3.533 seconds.  ( 3533 milliseconds )

作为一种便利方法......

double elapsedSeconds( org.joda.time.DateTime start, org.joda.time.DateTime stop )
{
    org.joda.time.Interval interval = new org.joda.time.Interval( start, stop );
    long milliseconds = interval.toDurationMillis();
    double seconds = ( (double)milliseconds / 1000 );
    return seconds;
}

使用示例......

System.out.println( "Calculating Elapsed: " + myObject.elapsedSeconds(now, aMomentLater) );