如果做一个新的日期(0L),时代不是时代。为什么? [英] Epoch is not epoch if do a new Date(0L). Why?
问题描述
我的问题很简单:
如果我这样做:
public class Main {
public static void main(String[] args) throws Exception {
Date d = new Date(0L );
System.out.println(d);
}
}
我得到以下输出:星期四1月01日01:00:00 CET 1970
I get the following output : Thu Jan 01 01:00:00 CET 1970
根据文件,我期待:Thu Jan 01 00:00:00 CET 1970
According to the doc, I was expecting : Thu Jan 01 00:00:00 CET 1970
我想错了...
编辑:
的确,我读得太快了。我应该在1970年1月1日00:00:00 GMT 1970年
EDIT : Indeed, I read the doc too fast. I should have Thu Jan 01 00:00:00 GMT 1970
那么,我如何强制使用GMT,并忽略所有当地时间?
So, how can I force the use of GMT, and ignore all local time ?
编辑,解决方案:
public static void main(String[] args) throws Exception {
SimpleDateFormat sdf = new SimpleDateFormat("H:m:s:S");
SimpleTimeZone tz = new SimpleTimeZone(0,"ID");
sdf.setTimeZone(tz) ;
Date d = new Date(0L );
System.out.println( sdf.format(d));
}
推荐答案
纪元定义为1970-1-1 UTC的00:00:00。由于 CET 为UTC + 1,因此您的时间等于凌晨1点。
The Epoch is defined as 00:00:00 on 1970-1-1 UTC. Since CET is UTC+1, it's equal to 1AM your time.
如果你看一下日期(长)构造函数,你会发现它希望该值是自纪元以来的毫秒数, UTC :
If you look at the Date(long) constructor, you'll see that it expects the value to be the number of milliseconds since the epoch, UTC:
分配Date对象并初始化
它代表
指定的毫秒数,自从
标准基准时间称为
纪元,即1970年1月1日,
00:00:00 GMT。 / p>
Allocates a Date object and initializes it to represent the specified number of milliseconds since the standard base time known as "the epoch", namely January 1, 1970, 00:00:00 GMT.
关于强制GMT而不是本地时区的愿望:简而言之,Date实例总是使用格林威治标准时间。如果你只是想格式化输出字符串,以便它使用GMT有一个 DateFormat 类,特别是它的 setTimeZone()方法。
Regarding your desire to force GMT instead of your local time zone: In short, the Date instance always uses GMT. If you just want to format the output String so that it uses GMT have a the DateFormat class, and specifically, its setTimeZone() method.
这篇关于如果做一个新的日期(0L),时代不是时代。为什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!