Reputation: 7519
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
Upvotes: 0
Views: 150
Reputation: 5317
You can get this in following steps:
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.
Upvotes: 2
Reputation: 26919
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 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.
Upvotes: 2