【问题标题】:Converting from Milliseconds to UTC Time in Java在 Java 中从毫秒转换为 UTC 时间
【发布时间】:2015-07-08 12:00:15
【问题描述】:

我正在尝试将毫秒时间(自 1970 年 1 月 1 日以来的毫秒数)转换为 Java 中的 UTC 时间。我已经看到很多其他使用 SimpleDateFormat 来更改时区的问题,但我不确定如何将时间转换为 SimpleDateFormat,到目前为止,我只知道如何将其转换为字符串或日期.

因此,例如,如果我的初始时间值为 1427723278405,我可以使用 String date = new SimpleDateFormat("MMM dd hh:mm:ss z yyyy", Locale.ENGLISH).format(new Date (epoch)); 或 Date d = new Date(epoch); 将其设置为美国东部时间周一 3 月 30 日 09:48:45,但每当我尝试将其更改为 SimpleDateFormat 以执行某些操作时像this 我遇到问题是因为我不确定将日期或字符串转换为日期格式并更改时区的方法。

如果有人有办法做到这一点,我将不胜感激,谢谢!

【问题讨论】:

    标签: java date datetime simpledateformat


    【解决方案1】:

    java.time 选项

    您可以使用 Java 8 及更高版本中内置的新 java.time package。

    您可以创建一个ZonedDateTime 对应于 UTC 时区中的那个时刻:

    ZonedDateTime utc = Instant.ofEpochMilli(1427723278405L).atZone(ZoneOffset.UTC);
    System.out.println(utc);
    

    如果您需要不同的格式,也可以使用 DateTimeFormatter,例如:

    System.out.println( DateTimeFormatter.ofPattern("EEE MMM dd HH:mm:ss").format(utc));
    

    【讨论】:

      【解决方案2】:

      试试下面..

      package com.example;
      
      import java.text.SimpleDateFormat;
      import java.util.Date;
      import java.util.TimeZone;
      
      public class TestClient {
      
          /**
           * @param args
           */
          public static void main(String[] args) {
              long time = 1427723278405L;
              SimpleDateFormat sdf = new SimpleDateFormat();
              sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
              System.out.println(sdf.format(new Date(time)));
      
          }
      
      }
      

      【讨论】:

        【解决方案3】:

        你可以检查一下..

        Calendar calendar = new GregorianCalendar();
            calendar.setTimeInMillis(1427723278405L);
        
            DateFormat formatter = new SimpleDateFormat("dd MMM yyyy HH:mm:ss z");
        
            formatter.setCalendar(calendar);
        
            System.out.println(formatter.format(calendar.getTime()));
        
            formatter.setTimeZone(TimeZone.getTimeZone("America/New_York"));
        
            System.out.println(formatter.format(calendar.getTime()));
        

        【讨论】:

          猜你喜欢
          • 2017-04-25
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2015-12-16
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2015-10-23
          相关资源
          最近更新 更多