type seconds between Joda

I can get the integral number of seconds between two DateTimes using the Seconds class:

Seconds.secondsBetween(now, dateTime);

However, it's not clear to me how the Joda-Time API would have me get the difference with fractional seconds, ie seconds as a double? Do I need to calculate fractional seconds from milliseconds or ticks? The API is generally so elegant and expressive, I feel like I might be missing something...


Not too hard… Use the Interval class in Joda-Time 2.3.

Example code in 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 )");

When run…

Elapsed: 3.533 seconds.  ( 3533 milliseconds )

As a convenience method…

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;
}

Example usage…

System.out.println( "Calculating Elapsed: " + myObject.elapsedSeconds(now, aMomentLater) );
链接地址: http://www.djcxy.com/p/36730.html

上一篇: MySQL查询GROUP BY日/月/年

下一篇: 在乔达之间键入秒