如何使用Java将UTC中的毫秒计数作为UTC的日期时间打印?

时间:2021-01-17 16:01:23

I am trying to use Java to format a time in milliseconds into a date in UTC. I have the following code:

我正在尝试使用Java将以毫秒为单位的时间格式化为UTC中的日期。我有以下代码:

long ms = 1427590800000;
Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("UTC"), Locale.ROOT);
cal.setTimeInMillis(ms);
Date date = cal.getTime();
SimpleDateFormat dateFormat = new SimpleDateFormat("YYYY-MM-dd hh:mm:ss");
System.out.println(dateFormat.format(date)); // 2015-03-29 02:00:00

This is printing a time in BST (i.e. using the default time-zone) rather than UTC. It seems like the time-zone being set on the calendar has no bearing on the date being printed.

这是在BST中打印一个时间(即使用默认时区)而不是UTC。看起来日历上设置的时区与打印日期无关。

The actual time in UTC is shown by the following python snippet:

UTC中的实际时间由以下python片段显示:

import datetime
ms = 1427590800000
print datetime.datetime.utcfromtimestamp(ms/1000.0) # 2015-03-29 01:00:00

Setting the default JVM time-zone to "UTC" results in the correct date being printed, but this doesn't seem like a safe solution.

将默认JVM时区设置为“UTC”会导致打印正确的日期,但这似乎不是一个安全的解决方案。

1 个解决方案

#1


0  

You need to set the timezone to the formatter before formatting if you want a desired timezone.

如果需要所需的时区,则需要在格式化之前将时区设置为格式化程序。

Use dateFormat.setTimeZone(TimeZone.getTimeZone("UTC")); and then call dateFormat.format(date)

使用dateFormat.setTimeZone(TimeZone.getTimeZone(“UTC”));然后调用dateFormat.format(date)

#1


0  

You need to set the timezone to the formatter before formatting if you want a desired timezone.

如果需要所需的时区,则需要在格式化之前将时区设置为格式化程序。

Use dateFormat.setTimeZone(TimeZone.getTimeZone("UTC")); and then call dateFormat.format(date)

使用dateFormat.setTimeZone(TimeZone.getTimeZone(“UTC”));然后调用dateFormat.format(date)