正如我所提到的,我没有得到两个时间戳的区别。我必须计算航班的持续时间。我到目前为止所做的代码是
public static void jodaDifference()
{
String departure= "2016-05-3122:05:00";
String arrival= "2016-06-0107:35:00";
//HH converts hour in 24 hours format (0-23), day calculation
DateTimeFormatter format = DateTimeFormat.forPattern("yyyy-mm-ddHH:mm:ss");
DateTime d1 = null;
DateTime d2 = null;
try {
d1 = format.parseDateTime(departure);
d2 = format.parseDateTime(arrival);
Duration duration = new Duration(d1, d2);
System.out.println(duration.getStandardDays());
System.out.println(duration.getStandardHours());
System.out.println(duration.getStandardMinutes());
System.out.print(Days.daysBetween(d1, d2).getDays() + " days, ");
System.out.print(Hours.hoursBetween(d1, d2).getHours() % 24 + " hours, ");
System.out.print(Minutes.minutesBetween(d1, d2).getMinutes() % 60 + " minutes, ");
System.out.print(Seconds.secondsBetween(d1, d2).getSeconds() % 60 + " seconds.");
final Period period = new Period(d1, d2);
System.out.print(period.getDays() + " days, ");
System.out.print(period.getHours() + " hours, ");
System.out.print(period.getMinutes() + " minutes, ");
System.out.print(period.getSeconds() + " seconds.");
System.out.println(""+Days.daysBetween(d1.withTimeAtStartOfDay(), d2.withTimeAtStartOfDay()).getDays());
}catch(Exception ex)
{
}
}
输出:
30
-734
-44070
-30 days, -14 hours, -30 minutes, 0 seconds.-2 days, -14 hours,-30 minutes,0 seconds.-30
此代码计算一些时间戳的错误差异,并为其他人完美工作。请帮助我......
答案 0 :(得分:0)
至少你的模式是错误的,因为你必须使用符号" M"几个月的时间" m"代表分钟。
关于使用多个单位表示持续时间的另一件事:Joda-Time为此目的提供了类Period
和PeriodFormatter
。使用你自己开发的逻辑构建多单元持续时间(在Joda-Time中称为句点)是错误的并且令人惊讶地尴尬。让Joda-Time为你做这份工作。
Joda-Time中的解决方案:
String departure = "2016-05-3122:05:00";
String arrival = "2016-06-0107:35:00";
DateTimeFormatter f = DateTimeFormat.forPattern("yyyy-MM-ddHH:mm:ss");
LocalDateTime ldt1 = f.parseLocalDateTime(departure);
LocalDateTime ldt2 = f.parseLocalDateTime(arrival);
Period p = new Period(ldt1, ldt2, PeriodType.dayTime());
System.out.println("Hour part: " + p.getHours()); // 9
System.out.println("Minute part: " + p.getMinutes()); // 30
System.out.println(PeriodFormat.wordBased(Locale.ENGLISH).print(p));
// output: 9 hours and 30 minutes
这适用于大约13种语言。简短形式的单位,如" hrs"或"分钟"除非您愿意使用PeriodFormatterBuilder
和固定文字(仅限一种语言),否则不会直接支持。