简体   繁体   中英

How to convert a time to UTC and then device local time

I am getting following time from service

'Nov 11 2019 7:30 PM'

I know this is US Central Time, I need to get hours between current time and this event time, but i am unable to understand how to convert this date to UTC.

I am using following approach, but this does not seem to be working fine.

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;
}   

This method returns following date

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

Although the expected output may be something like this. My device is at (+5:00 UTC)

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

You can get this in following steps:

  1. Use ZonedDateTime.parse to parse the time you are receiving.
  2. Convert the America Central time to your local time.
  3. Get your current time.
  4. Find the difference between your current time and the event time converted to your local.

Example:

    // 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());

The duration class provides many other utilities methods to get more precise duration.

You can use `LocalDateTime' to parse the string to date,

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

Then convert it to your preferred zone,

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

This will return an Instant .

And as Ole VV suggested in the comment, I wouldn't recommend using old Date and Calendar API. I would suggest reading this answer to understand the issues associated with the old Date API.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM