微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

如何解决给出错误时间的简单日期格式

我有一个以毫秒为单位的时间: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

我的代码有什么问题?

解决方法

在您的示例中,您使用的是时间 1618274313,并且您假设它以毫秒为单位。但是,当我在 https://www.epochconverter.com/ 的同一时间输入时,我得到以下结果:

请注意网站提及:Assuming that this timestamp is in seconds


现在,如果我们使用该数字乘以 1000 (1618274313000) 作为输入,以便网站在 毫秒 内考虑它,我们会得到以下结果:

请注意该网站现在提到:Assuming that this timestamp is in milliseconds


现在,当您将 1618274313000(以毫秒为单位的正确时间)在 Java 中与 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);

它将输出打印为 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));

输出为:

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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。