表达式
new Timestamp( Math.abs(diff/(1000*60*60*24)));
从领域的角度来看,在语义上是错误的。为什么?您尝试将时间量(实际上是以毫秒为单位的持续时间未锚定在时间线上)转换为此处固定为从 UNIX 纪元(1970-01-01)开始计数的时间点。这就像用几何术语将长度转换为点。
两个时间戳之间的差异不应该是一个新的时间戳,而应该只是一个持续时间(这里是您的差异变量,以毫秒为单位)。如何将其标准化为年和月取决于您。
OP 回答后更新
清洁 Joda 解决方案:
public static void main(String... args) {
Timestamp t1 = new Timestamp(0);
Timestamp t2 = new Timestamp(86400000 + 7261000);
System.out.println(getDurationJoda(t1, t2));
// output: 1 day, 2 hours, 1 minute, 1 second.
}
public static String getDurationJoda(Timestamp start, Timestamp end) {
LocalDateTime ldtStart = new LocalDateTime(start);
LocalDateTime ldtEnd = new LocalDateTime(end);
Period p = new Period(ldtStart, ldtEnd, PeriodType.dayTime());
PeriodFormatter fmt =
new PeriodFormatterBuilder()
.appendDays().appendSuffix(" day, ", " days, ")
.appendHours().appendSuffix(" hour, ", " hours, ")
.appendMinutes().appendSuffix(" minute, ", " minutes, ")
.appendSeconds().appendSuffix(" second.", " seconds.").toFormatter();
return fmt.print(p);
}
Time4J-解决方案
此外,您还可以使用我的库 Time4J 进行此替代,其中包含一个可本地化的 PrettyTime-class,用于从版本 1.2 开始的持续时间格式:
private static final IsoUnit DAYS = CalendarUnit.DAYS;
private static final IsoUnit HOURS = ClockUnit.HOURS;
private static final IsoUnit MINUTES = ClockUnit.MINUTES;
private static final IsoUnit SECONDS = ClockUnit.SECONDS;
public static void main(String... args) {
Timestamp t1 = new Timestamp(0);
Timestamp t2 = new Timestamp(86400000 + 7261000);
System.out.println(getDurationTime4J(t1, t2));
// output: 1 day, 2 hours, 1 minute, and 1 second
}
public static String getDurationTime4J(Timestamp start, Timestamp end) {
PlainTimestamp startTS = TemporalTypes.SQL_TIMESTAMP.transform(start);
PlainTimestamp endTS = TemporalTypes.SQL_TIMESTAMP.transform(end);
Duration<?> duration =
Duration.in(DAYS, HOURS, MINUTES, SECONDS).between(startTS, endTS);
return PrettyTime.of(Locale.ENGLISH).print(duration, TextWidth.WIDE);
}
最后但同样重要的是,在格式化持续时间之前尝试评估您的字符串条件并使用 equals() 而不是 ==,例如:
if (VEH_NUM.equals(vehicleNum)) {
// call getDuration(..., ...)
} else {
// return zero duration string
}