簡體   English   中英

日期格式化程序產生不一致的結果

[英]Date formatter produces inconsistent results

我想顯示格式化的日期而不是時間戳。 我的代碼:

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; dr

Instant.ofEpochMilli( yourLongNumber );
       .toString()

細節

舊的日期時間類有許多缺陷,其中之一就是缺乏線程安全性。

使用取代麻煩的舊類的java.time類。 java.time類使用不可變對象,並且是線程安全的。

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

2017-01-23T12:34:56.789Z

如果您不喜歡T,請調用String::replace或使用DateTimeFormatter 兩者都在其他有關堆棧溢出的問答中得到了展示。

為了靈活設置格式,請將基本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格式。 標准格式非常適合記錄日志,這似乎是您的Question的領域。

您期望的格式不明智,因為它沒有偏移或區域的指示。 這種缺失可能導致人們對偏移量/區域做出錯誤的假設,並誤解了他們正在閱讀的內容。 因此,我強烈建議您始終包含偏移量/區域信息。 我還建議您在UTC中進行所有登錄。 程序員和管理員都應學習將UTC視為“真實時間”。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM