问题描述
我尝试使用SimpleDateFormat格式化时间间隔。
I try to format a time interval using SimpleDateFormat.
import java.text.*;
import java.util.*;
public class DateFormatTest {
public static void main(String[] args) {
SimpleDateFormat sdf = new SimpleDateFormat("hh:mm:ss");
long interval = 1000;
System.out.println("Interval in millis: " + interval);
System.out.println("Expected result: 00:00:01");
System.out.println("Result using Date and SimpleDateFormat: " +
sdf.format(new Date(interval)));
}
}
我得到以下结果:
Interval in millis: 1000
Expected result: 00:00:01
Result using Date and SimpleDateFormat: 01:00:01
我在GMT + 1时区。
I am in GMT+1 time zone. But it should not be reflected in the result.
当然可以用System.out.printf来解决,但是我要搜索的是原因。
Of course it can be solved with System.out.printf, but what I am searching is the reason.
推荐答案
然后您应该在 SimpleDateFormat 。
SimpleDateFormat
在做准确正确的事情-它正在格式化时间点(1970年午夜 UTC 之后)。
Then you should set the time zone in the
SimpleDateFormat
. SimpleDateFormat
is doing exactly the right thing - it's formatting the instant in time (just after midnight UTC 1970) in the time zone it's working in.
要更改时区,只需使用:
To change the time zone, just use:
sdf.setTimeZone(TimeZone.getTimeZone("etc/UTC"));
尚不清楚您是否真的应该使用 SimpleDateFormat
。您并不是要格式化日期/时间,而是要格式化 interval (给定变量名)。
It's not clear whether you should really be using SimpleDateFormat
at all, though. You're not trying to format a date/time - you're trying to format an interval, given your variable name.
我建议您使用,它具有很多丰富的类型系统,并且可以来表达您真正想要的东西。
I suggest you use Joda Time which has a much richer type system, and will allow you to express what you really want.
此外,如果您真正想要使用 SimpleDateFormat
,您可能希望在格式字符串中使用 HH
而不是 hh
。 ( hh
是12小时值1-12。您要00:00:01,而不是12:00:01。) hh
在您的图案中也没有 表示am / pm的情况下,很少使用。
Also, if you really want to use SimpleDateFormat
, you probably want to use HH
instead of hh
in your format string. (hh
is a 12-hour value, 1-12. You want 00:00:01, not 12:00:01.) hh
is rarely appropriate when you don't also have an am/pm designator in your pattern.
这篇关于SimpleDateFormat无法格式化日期间隔?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!