gpt4 book ai didi

java - 日期格式化程序产生不一致的结果

转载 作者:行者123 更新时间:2023-12-02 02:52:50 24 4
gpt4 key购买 nike

我想显示格式化日期而不是时间戳。我的代码:

private static final String CRAWLER_DATE_FORMAT = "dd-MM-yyyy HH:mm:ss";
protected static final DateFormat DATE_FORMAT = new SimpleDateFormat(CRAWLER_DATE_FORMAT);

此日志行每 3 秒调用一次:

LOG.error("Timestamp: " + timestampString + " Formatted Date: " + DATE_FORMAT.format(Long.parseLong(timestampString));

我的日志:

Timestamp: 1491078405854 Formatted Date: 16-04-2017 21:25:20 <==
Timestamp: 1491078405854 Formatted Date: 01-04-2017 23:26:45
Timestamp: 1491078405854 Formatted Date: 01-04-2017 23:26:45
Timestamp: 1491078405854 Formatted Date: 01-04-2017 23:26:45
Timestamp: 1491078405854 Formatted Date: 01-04-2017 23:26:45
Timestamp: 1491078405854 Formatted Date: 16-04-2017 21:25:20 <==
Timestamp: 1491078405854 Formatted Date: 01-04-2017 23:26:45

为什么我得到不同的结果?

最佳答案

tl;博士

Instant.ofEpochMilli( yourLongNumber );
.toString()

详细信息

旧的日期时间类有许多缺陷,其中之一就是缺乏线程安全性。

使用 java.time 类来取代麻烦的遗留类。 java.time 类使用不可变对象(immutable对象)并且是线程安全的。

Instant instant = Instant.ofEpochMilli( yourLongNumber );
String output = instant.toString();

2017-01-23T12:34:56.789Z

如果您不喜欢 T,请调用 String::replace 或使用 DateTimeFormatter。两者都出现在 Stack Overflow 上的许多其他问题和解答中。

为了提高格式设置的灵 active ,请将基本的 Instant 转换为 OffsetDateTime 对象。

DateTimeFormatter f = DateTimeFormatter.ofPattern( "dd-MM-uuuu HH:mm:ss" , Locale.US );
String output = instant.atOffset( ZoneOffset.UTC ).format( f );

只要有可能,我建议坚持使用 java.time 类中默认使用的标准 ISO 8601 格式。标准格式非常适合记录,这似乎是您问题的领域。

您想要的格式不明智,因为它缺少偏移量或区域的指示。这种缺乏可能会导致人们对偏移/区域做出错误的假设并误解他们正在阅读的内容。所以我强烈建议始终包含偏移/区域信息。我还建议您使用 UTC 进行所有日志记录。程序员和管理员都应该学会将 UTC 视为唯一的真实时间。

关于java - 日期格式化程序产生不一致的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43546485/

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