San*_*eep 1 java timezone datetime date utc
一个老堆栈溢出发帖建议得到Java中的UTC时间戳的方式如下:
Instant.now() // Capture the current moment in UTC.
Run Code Online (Sandbox Code Playgroud)
不幸的是,这对我不起作用。我有一个非常简单的程序(转载如下),它展示了不同的行为。
在 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);
}
}
Run Code Online (Sandbox Code Playgroud)
窗口输出:
C:\tmp>java UTCTimeDisplayer
Windows 10
Current UTC time is Fri Jan 22 14:28:59 GMT-06:00 2021
Run Code Online (Sandbox Code Playgroud)
Linux输出:
/tmp> java UTCTimeDisplayer
Linux
Current UTC time is Fri Jan 22 14:31:10 MST 2021
Run Code Online (Sandbox Code Playgroud)
该对象不是像现代日期时间类型那样java.util.Date的真正的日期时间对象;相反,它表示自称为“纪元”的标准基准时间(或 UTC)以来的毫秒数。当您打印 的对象时,其方法会返回 JVM 时区中的日期时间(根据该毫秒值计算得出)。如果您需要打印不同时区的日期时间,则需要将时区设置为并从中获取格式化字符串。January 1, 1970, 00:00:00 GMTjava.util.DatetoStringSimpleDateFormat
我建议您只需使用Instant.now()它即可转换为其他java.time类型。
日期时间 APIjava.util及其格式化 APISimpleDateFormat已过时且容易出错。建议完全停止使用它们并切换到现代日期时间 API。
但是,如果您仍然想使用java.util.Date,请SimpleDateFormat按照上面提到的方式使用。
演示:
import java.text.SimpleDateFormat;
import java.time.Instant;
import java.util.Date;
import java.util.TimeZone;
public class Main {
public static void main(String[] args) {
Date currentUtcTime = Date.from(Instant.now());
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss z");
sdf.setTimeZone(TimeZone.getTimeZone("Etc/UTC"));
System.out.println("Current UTC time is " + sdf.format(currentUtcTime));
}
}
Run Code Online (Sandbox Code Playgroud)
输出:
Current UTC time is 2021-01-22 21:53:07 UTC
Run Code Online (Sandbox Code Playgroud)
您的代码:
Date.from(Instant.now())
Run Code Online (Sandbox Code Playgroud)
您将可怕的遗留类与其替代品(现代java.time类)混合在一起。
别。
永远不要使用Date. 当然没必要混用java.time.Instant。
为了解释您的特定示例,请了解在Date该类的许多糟糕设计选择中,其Date#toString方法的反特性是在生成其文本时隐式应用 JVM 的当前默认时区。
您在具有不同当前默认时区的两个不同 JVM 上运行您的代码。所以你得到了不同的输出。
Sun、Oracle 和 JCP 放弃了遗留的日期时间类。我们都应该如此。我建议你不花时间试图了解Date,Calendar,SimpleDateFormat,和这样的。
你问:
问题:我们如何在 Java 程序中显示 UTC 时间戳?
Instant.now().toString()
Run Code Online (Sandbox Code Playgroud)
2021-01-22T21:50:18.887335Z
你说:
在 Windows 上:...
在 Linux 上:...
您将Instant.now().toString()在 Windows、Linux、BSD、macOS、iOS、Android、AIX 等平台上获得相同的一致结果。
这是我制作的表格,用于指导您从遗留课程过渡。
