在Java中获取UTC时间戳

一个老堆栈溢出发帖建议得到Java中的UTC时间戳的方式如下:

Instant.now()   // Capture the current moment in UTC.

不幸的是,这对我不起作用。我有一个非常简单的程序(转载如下),它展示了不同的行为。

在 Windows 上:时间是本地时间,并标有 GMT 的偏移量

在 Linux 上:时间再次是本地时间,并且为本地时区正确标记了时间


问题:我们如何在 Java 程序中显示 UTC 时间戳?


我的示例源代码如下:

import java.time.Instant;
import java.util.Date;

public class UTCTimeDisplayer {
    public static void main(String[] args) {
        System.out.println(System.getProperty("os.name"));
        Date currentUtcTime = Date.from(Instant.now());
        System.out.println("Current UTC time is " + currentUtcTime);
    }
}  

窗口输出:

C:tmp>java UTCTimeDisplayer
Windows 10
Current UTC time is Fri Jan 22 14:28:59 GMT-06:00 2021

Linux输出:

/tmp> java UTCTimeDisplayer
Linux
Current UTC time is Fri Jan 22 14:31:10 MST 2021

回答

您的代码:

Date.from(Instant.now())

您将可怕的遗留类与其替代品(现代java.time类)混合在一起

别。

永远不要使用Date. 当然没必要混用java.time.Instant

为了解释您的特定示例,请了解在Date该类的许多糟糕设计选择中,其Date#toString方法的反特性是在生成其文本时隐式应用 JVM 的当前默认时区

您在具有不同当前默认时区的两个不同 JVM 上运行您的代码。所以你得到了不同的输出。

Sun、Oracle 和 JCP 放弃了遗留的日期时间类。我们都应该如此。我建议你不花时间试图了解DateCalendarSimpleDateFormat,和这样的。

你问:

问题:我们如何在 Java 程序中显示 UTC 时间戳?

Instant.now().toString()

在 IdeOne.com 上查看实时运行的代码。

2021-01-22T21:50:18.887335Z

你说:

在 Windows 上:...

在 Linux 上:...

您将Instant.now().toString()在 Windows、Linux、BSD、macOS、iOS、Android、AIX 等平台上获得相同的一致结果。


这是我制作的表格,用于指导您从遗留课程过渡。


以上是在Java中获取UTC时间戳的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>