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

问题描述 投票:0回答:4

我的时间以毫秒为单位:

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

我的代码有什么问题?

java date simpledateformat epoch
4个回答
4
投票

在您的示例中,您使用的是时间

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

2
投票

使用 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


1
投票

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


0
投票

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

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

打印

PT449H31M14.313S

这表示持续时间为 449 小时 31 分 14.313 秒。 如果不知道该持续时间的纪元和任何适用的区域偏移量,实际上不可能确定它代表的具体日期/时间。我可以做出很多假设并据此提供结果,但您提供的更多信息将会有所帮助。

© www.soinside.com 2019 - 2024. All rights reserved.