簡體   English   中英

給出錯誤時間的簡單日期格式

[英]Simple date format giving wrong time

我有一個以毫秒為單位的時間: 1618274313

當我使用此網站將其轉換為時間時: https://www.epochconverter.com/ ,我得到6:08:33 AM

但是當我使用SimpleDateFormat時,我得到了一些不同的東西:

SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss", Locale.getDefault());
System.out.println(sdf.format(new Date(1618274313)));

我得到 output 為23:01:14

我的代碼有什么問題?

在您的示例中,您使用的是時間1618274313並且您假設它以毫秒為單位 但是,當我在https://www.epochconverter.com/上同時輸入時,我得到以下結果:

請注意該站點提到: Assuming that this timestamp is in seconds


現在,如果我們使用該數字乘以1000 ( 1618274313000 ) 作為輸入,以便網站以毫秒為單位考慮它,我們會得到以下結果:

請注意該站點現在提到: Assuming that this timestamp is in milliseconds


現在,當您將 Java 中的1618274313000 (以毫秒為單位的正確時間)與SimpleDateFormat一起使用時,您應該得到預期的結果(而不是23:01:14 ):

SimpleDateFormat sdf=new SimpleDateFormat("HH:mm:ss", Locale.getDefault());
System.out.println(sdf.format(new Date(1618274313000)));

使用 Instant.ofEpochSecond

long test_timestamp = 1618274313L;
        LocalDateTime triggerTime =
                LocalDateTime.ofInstant(Instant.ofEpochSecond(test_timestamp), 
                                        TimeZone.getDefault().toZoneId());  

        System.out.println(triggerTime);

它將 output 打印為2021-04-13T06:08:33

假設您所說的以毫秒為單位,那么您可以肯定的是,您有一個特定的持續時間。

Duration d = Duration.ofMillis(1618274313);
System.out.println(d);

印刷

PT449H31M14.313S

這表示它的持續時間為 449 小時 31 分鍾和 14.313 秒。 在不知道此持續時間的紀元和任何適用的區域偏移量的情況下,實際上不可能確定它所代表的具體日期/時間。 我可以做出很多假設並在此基礎上提供結果,但您提供的更多信息會有所幫助。

java.time

正如 Viral Lalakia 已經發現的那樣,您鏈接到的紀元轉換器明確表示,它假定該數字是自紀元以來的秒數(而不是毫秒)。 下面在 Java 中做同樣的假設。 我建議您使用 java.time,現代 Java 日期和時間 API。

    ZoneId zone = ZoneId.of("Asia/Kolkata");
    
    long unixTimestamp = 1_618_274_313;
    
    Instant when = Instant.ofEpochSecond(unixTimestamp);
    ZonedDateTime dateTime = when.atZone(zone);
    
    System.out.println(dateTime);
    System.out.println(dateTime.format(DateTimeFormatter.ISO_LOCAL_TIME));

Output 是:

 2021-04-13T06:08:33+05:30[Asia/Kolkata] 06:08:33

這與您從轉換器獲得的6:08:33 AM一致。 並且日期是今天的日期。 巧合?

如果數字確實是毫秒(我真的懷疑),只需使用Instant.ofEpochMill()而不是Instant.ofEpochSecond()

    Instant when = Instant.ofEpochMilli(unixTimestamp);
 1970-01-19T23:01:14.313+05:30[Asia/Kolkata] 23:01:14.313

這反過來與您在 Java 中得到的結果一致(除了還打印了毫秒)。

暫無
暫無

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

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