为什么以下Java代码的输出是04:18:23而不是03:18:23?
public static void main(String[] args) {
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
try {
Date start = sdf.parse("00:44:16");
Date end = sdf.parse("04:02:39");
long duration = end.getTime() - start.getTime();
Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(duration);
System.out.println(sdf.format(cal.getTime()));
} catch (ParseException e) {
e.printStackTrace();
}
}
答案 0 :(得分:10)
因为这不是你获得持续时间的方式。将您的代码更改为:
package com.sandbox;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
public class Sandbox {
public static void main(String[] args) {
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
try {
Date start = sdf.parse("00:44:16");
Date end = sdf.parse("04:02:39");
long duration = end.getTime() - start.getTime();
Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(duration);
System.out.println(new SimpleDateFormat("yyyy MM dd HH:mm:ss").format(cal.getTime()));
} catch (ParseException e) {
e.printStackTrace();
}
}
}
您会看到它打印出1969 12 31 19:18:23
。这是日期而非持续时间。由于您在打印答案时正在跳过日期组件,因此会出现,就像打印出一段时间一样,但事实并非如此。
坦率地说,我不知道如何在java中做到这一点。我只是使用JodaTime库。有一个名为Duration的课程让这很容易。这是一个SO问题,展示如何使用它以任何方式打印结果:"pretty print" duration in java
答案 1 :(得分:3)
或者,如果您不想使用JodaTime,从持续时间(毫秒)计算小时,分钟和秒非常简单:
public static void main(String[] args) throws ParseException {
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
Date start = sdf.parse("00:44:16");
Date end = sdf.parse("04:02:39");
long durationMs = end.getTime() - start.getTime();
final int oneHourMs = 3600000;
final int oneMinuteMs = 60000;
final int oneSecondMs = 1000;
long hours = durationMs / oneHourMs;
long minutes = (durationMs % oneHourMs) / oneMinuteMs;
long seconds = (durationMs % oneMinuteMs) / oneSecondMs;
System.out.format("%02d:%02d:%02d", hours, minutes, seconds);
// outputs: 03:18:23
}
答案 2 :(得分:0)
问题:
LocalTime
类表示没有日期且没有时区的时间值。
LocalTime start = LocalTime.parse( "00:44:16" );
LocalTime stop = LocalTime.parse( "04:02:39" );
Duration
表示未附加到时间轴的时间跨度。
Duration duration = Duration.between ( start , stop );