gpt4 book ai didi

java - 如果执行新日期(0L),则纪元不是纪元。为什么?

转载 作者:搜寻专家 更新时间:2023-11-01 01:15:01 25 4
gpt4 key购买 nike

我的问题解释得很直接:

如果我这样做:

public class Main {

public static void main(String[] args) throws Exception {
Date d = new Date(0L );
System.out.println(d);
}

}

我得到以下输出:Thu Jan 01 01:00:00 CET 1970

根据文档,我期待:Thu Jan 01 00:00:00 CET 1970

我想哪里出错了...

编辑:确实,我阅读文档的速度太快了。我应该有 Thu Jan 01 00:00:00 GMT 1970

那么,我怎样才能强制使用 GMT,而忽略所有本地时间呢?

编辑,解决方案:

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));
}

最佳答案

Epoch定义为 1970-1-1 UTC 的 00:00:00。自 CET是UTC+1,等于你的时间凌晨1点。

如果您查看 Date(long)构造函数,你会看到它期望值是自纪元以来的毫秒数,UTC :

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。如果您只想格式化输出字符串,使其使用 GMT,则可以使用 DateFormat类,特别是它的 setTimeZone()方法。

关于java - 如果执行新日期(0L),则纪元不是纪元。为什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2434557/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com