【问题标题】:Issue converting local time to UTC [duplicate]将本地时间转换为 UTC 的问题 [重复]
【发布时间】:2014-01-12 09:18:24
【问题描述】:

我尝试使用以下代码将本地日期时间转换为 UTC 日期时间。但他们来的一样。我想我在这里遗漏了一些东西。谁能帮助我如何从本地日期时间10/15/2013 09:00 AM GMT+05:30 获取 UTC 日期时间。这个日期时间字符串是我从外部系统获得的,因此如果需要,我可以更改格式。

SimpleDateFormat outputFormatInUTC = new SimpleDateFormat("MM/dd/yyyy hh:mm aaa z");
String startDateTime = "10/15/2013 09:00 AM GMT+05:30";
Date utcDate = outputFormatInUTC.parse(startDateTime);

【问题讨论】:

    标签: java date datetime


    【解决方案1】:

    只需设置TimeZone:

    SimpleDateFormat outputFormatInUTC = new SimpleDateFormat("MM/dd/yyyy hh:mm aaa z");
    String startDateTime = "10/15/2013 09:00 AM GMT+05:30";
    outputFormatInUTC.setTimeZone(TimeZone.getTimeZone("UTC"));  
    Date utcDate = outputFormatInUTC.parse(startDateTime);
    String timeInUTC = outputFormatInUTC.format(utcDate);
    System.out.println(timeInUTC);
    

    输出:

    10/15/2013 03:30 AM UTC
    

    【讨论】:

    • 感谢您的回复。在这里,我首先获取日期对象,然后再次将日期作为字符串获取,所以现在如果我需要一个日期对象,我必须再次将此字符串传输到一个日期对象。我对么?如果是,有没有更好的方法?
    • 没有,我们先设置SimpleDateFormat->配置时区->解析字符串日期->根据DateFormat提取合适的String日期。
    • 所以现在我有了 UTC 格式的日期字符串。我怎样才能把它转移到一个日期。
    【解决方案2】:

    试试这个:

        SimpleDateFormat outputFormatInUTC = new SimpleDateFormat("MM/dd/yyyy hh:mm aaa z");
        System.out.println(new Date()); //prints local date-time
        outputFormatInUTC.setTimeZone(TimeZone.getTimeZone("UTC"));
        System.out.println(outputFormatInUTC.format(new Date())); //prints UTC date-time
    

    【讨论】:

      【解决方案3】:

      ISO 8601 格式

      是的,如果您可以更改字符串的格式,您应该这样做。为此目的存在一个国际标准:ISO 8601。喜欢这个2013-12-26T21:19:39+00:00 或这个2013-12-26T21:19Z

      乔达时间

      避免使用 java.util.Date/Calendar 类。他们是出了名的坏。 Java 8 用新的 java.time.* JSR 310 类取代了它们。同时,您可以使用启发 JSR 310 的 Joda-Time 库。

      我下面的示例代码使用在 Mac 上以 Java 7 运行的 Joda-Time 2.3。

      示例代码

      // © 2013 Basil Bourque. This source code may be used freely forever by anyone taking full responsibility for doing so.
      // import org.joda.time.*;
      // import org.joda.time.format.*;
      
      String string = "10/15/2013 09:00 AM GMT+05:30";
      DateTimeFormatter formatter = DateTimeFormat.forPattern( "MM/dd/yyyy hh:mm aaa zZ" );
      DateTime dateTime = formatter.parseDateTime( string );
      System.out.println( "dateTime: " + dateTime );
      

      运行时……

      dateTime: 2013-10-15T03:30:00.000Z
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-03-01
        • 1970-01-01
        • 2018-07-27
        • 1970-01-01
        • 2011-10-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多