Java的时差 [英] Time difference in Java
问题描述
为什么以下Java代码的输出是04:18:23而不是03:18:23?
Why the output of the Java code below is 04:18:23 and not 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();
}
}
推荐答案
因为这不是你如何得到一个持续时间。将您的代码更改为:
Because that's not how you get a duration. Change your code to this:
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();
}
}
}
你会看到它打印out 1969 12 31 19:18:23
。那是日期而不是持续时间。由于您在打印答案时正在跳过日期组件,因此它出现就像打印一段时间一样,但事实并非如此。
You'll see it prints out 1969 12 31 19:18:23
. That's a date not a duration. Since you're skipping the date components when you print out your answer, it appears like it's printing out a duration, but it's really not.
坦率地说,我不知道如何在java中这样做。我只是使用JodaTime库。有一个名为持续时间的课程,使这一切变得简单。这是一个SO问题,显示如何使用它以任何方式打印结果:"漂亮的印刷品持续时间在java
To be frank, I don't know how to do this in java. I just use the JodaTime library. There's a class called Duration that makes this easy. Here's a SO question that shows how to use it to print out the results any way you want: "pretty print" duration in java
这篇关于Java的时差的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!