Skip to content Skip to sidebar Skip to footer

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 un

Solution 1:

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

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

Then convert it to your preferred zone,

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

This will return an Instant.

And as Ole V.V 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.

Solution 2:

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.StringdateWithZone="Nov 11 2019 7:30 PM".concat("America/Chicago") ;
    DateTimeFormatterformatter= DateTimeFormatter.ofPattern("MMM dd uuuu h:m aVV");

    ZonedDateTimezonedDateTime= 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 zoneZonedDateTimeeventTimeInLocal= 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.

Post a Comment for "How To Convert A Time To Utc And Then Device Local Time"