简单的日期格式给出了错误的时间

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

我得到的输出是 23:01:14

我的代码有什么问题?

使用Instant.ofEpochSecond

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

        System.out.println(triggerTime);

它将输出打印为 2021-04-13T06:08:33

在您的示例中,您使用的是时间 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)));

假设如您所说,以毫秒为单位,您可以确定的是您有一个特定的持续时间。

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

版画

PT449H31M14.313S

也就是 449 小时 31 分 14.313 秒的时长。在不知道这段持续时间的纪元和任何适用的区域偏移量的情况下,实际上不可能确定它所代表的具体 date/time。我可以做出很多假设并据此提供结果,但您提供的更多信息会有所帮助。

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

输出为:

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 中得到的结果一致(除了还打印了毫秒)。