本文介绍了如何将时间转换为UTC,然后转换为设备本地时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在从服务中获取时间
I am getting following time from service
我知道这是美国中部时间,我需要获取当前时间与该事件时间之间的小时数,但是我无法理解如何将该日期转换为UTC.
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;
}
此方法返回date
Fri Oct 11 12:30:00 GMT+05:00 2019
尽管预期的输出可能是这样的.我的设备位于(+5:00 UTC)
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:
- 使用 ZonedDateTime.parse 来解析您收到的时间.
- 将美国中部时间"转换为您当地的时间.
- 获取您的当前时间.
- 查找当前时间与转换为本地时间的事件时间之间的时差.
- Use ZonedDateTime.parse to parse the time you are receiving.
- Convert the America Central time to your local time.
- Get your current time.
- Find the difference between your current time and the event time converted to your local.
示例:
// 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类提供了许多其他实用程序方法来获得更精确的持续时间.
The duration class provides many other utilities methods to get more precise duration.
这篇关于如何将时间转换为UTC,然后转换为设备本地时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!