【问题标题】:How can I convert epoch time to date and time in Java?如何在 Java 中将纪元时间转换为日期和时间?
【发布时间】:2011-12-13 01:34:05
【问题描述】:

我需要将纪元时间戳转换为日期和时间。 我已使用以下代码进行转换,但它转换为错误的日期、年份和时间。

String date = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss")
                    .format(new java.util.Date (1319286637/1000));

预期的输出是今天某个时间的日期,但我得到的结果是:

01/01/1970 05:51:59

【问题讨论】:

    标签: java datetime time epoch


    【解决方案1】:

    Date(long) 构造函数需要几毫秒。您应该乘以 1000,而不是除以您拥有的纪元时间。

    【讨论】:

      【解决方案2】:

      简而言之:

      Instant.ofEpochSecond( 1_319_286_637L )
      

      2011-10-22T12:30:37Z

      使用现代 API java.time 的解决方案:

      import java.time.Instant;
      
      public class Main {
          public static void main(String[] args) {
              Instant instant = Instant.ofEpochSecond(1319286637L);
              System.out.println(instant);
          }
      }
      

      输出:

      2011-10-22T12:30:37Z
      

      Instant 代表时间线上的一个瞬时点。输出中的 Z 是零时区偏移量的 timezone designator。它代表 Zulu,并指定 Etc/UTC 时区(时区偏移量为 +00:00 小时)。

      您可以将Instant 转换为其他日期时间类型,例如

      import java.time.Instant;
      import java.time.ZoneId;
      import java.time.ZonedDateTime;
      import java.time.format.DateTimeFormatter;
      import java.util.Locale;
      
      public class Main {
          public static void main(String[] args) {
              Instant instant = Instant.ofEpochSecond(1319286637);
              ZonedDateTime zdt = instant.atZone(ZoneId.of("Asia/Kolkata"));
              System.out.println(zdt);
      
              // A custom format
              DateTimeFormatter dtf = DateTimeFormatter.ofPattern("MM/dd/uuuu HH:mm:ss", Locale.ENGLISH);
              System.out.println(dtf.format(zdt));
          }
      }
      

      输出:

      2011-10-22T18:00:37+05:30[Asia/Kolkata]
      10/22/2011 18:00:37
      

      从Trail: Date Time了解更多关于java.time,modern Date-Time API*。

      注意:java.util 日期时间 API 及其格式化 API SimpleDateFormat 已过时且容易出错。建议完全停止使用它们并切换到modern Date-Time API*。但是,出于任何目的,如果您需要将Instant 的对象转换为java.util.Date 的对象,您可以这样做:

      Date date = Date.from(instant);
      

      * 出于任何原因,如果您必须坚持使用 Java 6 或 Java 7,您可以使用 ThreeTen-Backport,它将大部分 java.time 功能向后移植到 Java 6 和 7 . 如果您正在为一个 Android 项目工作并且您的 Android API 级别仍然不符合 Java-8,请检查 Java 8+ APIs available through desugaring 和 How to use ThreeTenABP in Android Project。

      【讨论】:

        猜你喜欢
        • 2012-09-06
        • 2018-04-24
        • 2011-12-06
        • 2018-12-27
        • 2019-06-19
        • 1970-01-01
        • 2015-06-22
        • 2018-10-01
        • 2010-12-14
        相关资源
        最近更新 更多