【问题标题】:How to use DateTime and Unix time in Java?如何在 Java 中使用 DateTime 和 Unix 时间?
【发布时间】:2020-02-28 11:31:03
【问题描述】:

我正在使用 Java 在 Android Studio 中制作适用于 Android 的应用程序。我正在处理日期和时间。我正在尝试从自定义的给定时间点生成 Unix 时间戳。比如下面这段代码

LocalDateTime aDateTime = LocalDateTime.of(2021, 4, 30, 8, 30);
ZoneId zoneId = ZoneId.systemDefault();
int x = Math.toIntExact(aDateTime.atZone(zoneId).toEpochSecond());

产生一个 Unix 时间戳 1619760600。但是,当我将它输入任何在线转换器时,它会产生一个时间 04/30/2021 @ 5:30am (UTC)。这与原始插入时间相差 3 hours,这是我的时区与 UTC00:00 不同的确切小时数。

问题似乎是我无法理解 Java 中的时区。所以我的问题是,我如何正确考虑时区以便生成正确的 UnixTimeStamp?

【问题讨论】:

    标签: java android datetime


    【解决方案1】:

    您已经有了正确的时间戳。

    时间戳代表时间的瞬间。仅当您想在用户的本地时间显示时间戳时,时区才重要。在您的情况下,04/30/2021 @ 5:30am (UTC) 与您当地时间上午 8:30 的时间相同。看看你找到的在线工具是否可以显示除UTC之外的本地时间的时间戳。

    您应该停止使用 int 作为时间戳,而是使用 long https://en.m.wikipedia.org/wiki/Year_2038_problem

    如果您希望为 8:30 UTC 而不是本地时间 8:30 创建时间戳,只需在创建分区日期时间时使用 UTC 时区:

    LocalDateTime aDateTime = LocalDateTime.of(2021, 4, 30, 8, 30);
    ZoneId zoneId = ZoneOffset.UTC;
    long x = aDateTime.atZone(zoneId).toEpochSecond();
    

    【讨论】:

      【解决方案2】:

      您可以利用java.time API(假设您使用的是Java 8)。这是一个示例,取您提供的信息:

      LocalDateTime localDateTime = LocalDateTime.of(2021, 4, 30, 8, 30);
      ZonedDateTime zdt = ZonedDateTime.of(localDateTime, ZoneId.systemDefault());
      long millis = zdt.toInstant().toEpochMilli();
      

      您可以找到更多信息here。希望对你有帮助

      【讨论】:

        【解决方案3】:

        按如下方式进行:

        import java.time.LocalDateTime;
        import java.time.ZoneId;
        
        public class Main {
            public static void main(String[] args) {
                LocalDateTime aDateTime = LocalDateTime.of(2021, 4, 30, 8, 30);
                ZoneId zoneIdUTC = ZoneId.of("UTC");
                ZoneId myZoneId = ZoneId.systemDefault();
                LocalDateTime bDateTime = aDateTime.atZone(zoneIdUTC).withZoneSameInstant(myZoneId).toLocalDateTime();
                System.out.println(bDateTime.atZone(myZoneId).toEpochSecond());
            }
        }
        

        输出:

        1619771400
        

        试试https://www.unixtimestamp.com/index.php

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2011-12-10
          • 1970-01-01
          • 2020-10-09
          • 1970-01-01
          • 2010-11-19
          • 2018-01-04
          • 2010-12-18
          • 1970-01-01
          相关资源
          最近更新 更多