2016-05-17 51 views
0

我有一个确定两个dateTime变量之间的时间段的方法。如何转换并将日期转换为java中Period类的几个小时?

Period period = new Period(startTime, endTime); 
PeriodFormatter runDurationFormatter = new PeriodFormatterBuilder().printZeroAlways().minimumPrintedDigits(2).appendDays().appendSeparator(":").appendHours().appendSeparator(":").appendMinutes().appendSeparator(":").appendSeconds().toFormatter(); 
return runDurationFormatter.print(period); 

我希望看到00:01:00 1分钟,23时00分00秒23小时,30:00:00 30小时,和120:00:00 120小时(5天)。 我尝试使用

Period daystoHours = period.normalizedStandard(PeriodType.time()); 

但是Eclipse表明normalizedStandard()方法是未定义型周期。

+0

的方法[Period.normalizedStandard()](http://www.joda.org/joda-time/apidocs/org/joda/time/Period.html#normalizedStandard-org.joda.time。 PeriodType-)自Joda-Time-v1.5以来就存在。确保a)你不使用旧的版本和b)使用正确的导入(请参阅@Gordeev的回答) –

回答

1

确保您使用org.joda.time包的Period类,而不是java.time。下面的例子可以帮助你。

import org.joda.time.Period; 
import org.joda.time.PeriodType; 
import org.joda.time.format.PeriodFormatter; 
import org.joda.time.format.PeriodFormatterBuilder; 

import java.util.Calendar; 
import java.util.GregorianCalendar; 

public class Launcher 
{ 
    public static void main(String[] args) 
    { 
     Calendar start = new GregorianCalendar(2016, 4, 12, 0, 0, 0); 
     Calendar end = new GregorianCalendar(2016, 4, 17, 0, 0, 0); 

     Period period = new Period(start.getTimeInMillis(), end.getTimeInMillis()); 

     PeriodFormatter runDurationFormatter = new PeriodFormatterBuilder().printZeroAlways() 
      .minimumPrintedDigits(2) 
      .appendHours().appendSeparator(":") // <-- say formatter to emit hours 
      .appendMinutes().appendSeparator(":") // <-- say formatter to emit minutes 
      .appendSeconds()      // <-- say formatter to emit seconds 
      .toFormatter(); 

     // here we are expecting the following result string 120:00:00 
     System.out.println(
      runDurationFormatter.print(period.normalizedStandard(PeriodType.time())) 
     ); 
    } 
} 
+0

感谢您的回复,但我无法使用period.normalizedStandard(PeriodType.time() ),它表示normalizedStandard在类型期间是未定义的。 – Shubham