【问题标题】:How to convert a time to UTC and then device local time如何将时间转换为 UTC,然后转换为设备本地时间
【发布时间】:2019-10-10 16:26:48
【问题描述】:

我正在从服务中获得以下时间

'2019 年 11 月 11 日晚上 7:30'

我知道这是美国中部时间,我需要获取当前时间和此事件时间之间的小时数,但我无法理解如何将此日期转换为 UTC。

我正在使用以下方法,但这似乎不能正常工作。

public Date ticketJSONDateFormatter(String dateTime){
    SimpleDateFormat simpleDateFormatter
            = new SimpleDateFormat("MMM d yyyy HH:mm a");
    
    Date parsedDate = null;
    try {
        simpleDateFormatter.setTimeZone(TimeZone.getTimeZone("UTC"));
        parsedDate = simpleDateFormatter.parse(dateTime);
    } catch (ParseException e) {
        e.printStackTrace();
    }
    return parsedDate;
}   

此方法返回date

Fri Oct 11 12:30:00 GMT+05:00 2019

虽然预期的输出可能是这样的。我的设备在 (+5:00 UTC)

Fri Oct 12 12:30:00 GMT+05:00 2019

【问题讨论】:

  • 您使用的是哪个版本的 Java?我问的原因是 Java >= 8 提供功能丰富的 date-dime api。
  • @techtabu: java 8
  • 我建议你不要使用SimpleDateFormatDate。这些类设计不佳且早已过时,尤其是前者,尤其是出了名的麻烦。而是使用LocalDateTimeZonedDateTimeDateTimeFormatter 和来自java.time, the modern Java date and time API 的其他类。

标签: java android date


【解决方案1】:

您可以使用 `LocalDateTime' 将字符串解析为日期,

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MMM dd yyyy hh:mm a");
String date = "Nov 11 2019 07:30 PM";
LocalDateTime ldt = LocalDateTime.parse(date, formatter);

然后将其转换为您的首选区域,

Instant cdt = ldt.atZone(ZoneId.of("America/Chicago")).toInstant();
return cdt.atOffset(ZoneOffset.UTC)

这将返回一个Instant

正如 Ole V.V 在评论中建议的那样,我不建议使用旧的 DateCalendar API。我建议阅读此answer 以了解与旧的Date API 相关的问题。

【讨论】:

    【解决方案2】:

    您可以通过以下步骤获得:

    1. 使用ZonedDateTime.parse 解析您收到的时间。
    2. 将美国中部时间转换为您的当地时间。
    3. 获取当前时间。
    4. 找出当前时间与转换为本地时间的事件时间之间的差异。

    例子:

        // Parsing the time you are receiving in Central Time Zone. Using Chicago as a representative Zone.
        String dateWithZone = "Nov 11 2019 7:30 PM".concat("America/Chicago") ;
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MMM dd uuuu h:m aVV");
    
        ZonedDateTime zonedDateTime = ZonedDateTime.parse(dateWithZone, formatter);
        System.out.println(zonedDateTime); // This is the time you received in Central time zone.
    
        // Now convert the event time in your local time zone
        ZonedDateTime eventTimeInLocal = zonedDateTime.withZoneSameInstant(ZoneId.systemDefault());
    
        // Then find the duration between your current time and event time
        System.out.println(Duration.between(ZonedDateTime.now(), eventTimeInLocal).toHours());
    

    duration 类提供了许多其他实用程序方法来获得更精确的持续时间。

    【讨论】:

    • @OleV.V.你是绝对正确的。我误读了,可能与unable to understand how to convert this date to UTC 混淆了。我现在更新了我的例子。无需将时间转换为 UTC 即可实现目标。
    猜你喜欢
    • 2013-03-23
    • 1970-01-01
    • 1970-01-01
    • 2018-07-27
    • 2013-01-28
    • 1970-01-01
    • 2013-08-13
    • 1970-01-01
    相关资源
    最近更新 更多