gpt4 book ai didi

Java 时间格式化

转载 作者:行者123 更新时间:2023-11-30 06:16:59 25 4
gpt4 key购买 nike

我有方法

public static void testDateFormat() throws ParseException {
DateFormat dateFormat=new SimpleDateFormat("HH:mm:ss");
Date hora;
hora=dateFormat.parse("00:00:01");
System.out.println(hora.getHours()+" "+hora.getMinutes());
System.out.println("Date "+hora);
System.out.println("Seconds "+TimeUnit.MILLISECONDS.toSeconds(hora.getTime()));
}

输出是

0 0
Date Thu Jan 01 00:00:01 COT 1970
Seconds 18001

为什么秒数是18001?我希望得到 1 秒。

最佳答案

因为您的 Date 有一个不是 UTC 的 TimeZone。事实上,它是 COT - 这是 UTC-5。而 5*60*60 是 18000(或你的结果,加上一秒)。要获得您期望的值,您可以调用 DateFormat#setTimeZone(TimeZone)喜欢,

DateFormat dateFormat=new SimpleDateFormat("HH:mm:ss");
dateFormat.setTimeZone(TimeZone.getTimeZone("UTC")); // <-- Add this.
Date hora=dateFormat.parse("00:00:01");
System.out.println(hora.getHours()+" "+hora.getMinutes());
System.out.println("Date "+hora);
System.out.println("Seconds "+TimeUnit.MILLISECONDS.toSeconds(hora.getTime()));

输出如你所料。

编辑如评论中所述,Date#getTime()根据 Javadoc

Returns the number of milliseconds since January 1, 1970, 00:00:00 GMT represented by this Date object.

还有你的日期

Thu Jan 01 00:00:01 COT 1970

相当于

Thu Jan 01 00:05:01 UTC 1970

因此您得到 5 小时的时差。

关于Java 时间格式化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26415225/

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