在乔达之间键入秒
我可以使用Seconds
类获取两个DateTime之间的整数Seconds
:
Seconds.secondsBetween(now, dateTime);
然而,我不清楚Joda-Time API如何让我用秒数获得差异,例如秒数是双倍数? 我需要从毫秒或滴答计算小数秒吗? 该API通常是如此优雅和富有表现力,我觉得我可能会错过一些东西......
不要太难...在Joda-Time 2.3中使用Interval类。
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) );
链接地址: http://www.djcxy.com/p/36729.html