【发布时间】: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
-
我建议你不要使用
SimpleDateFormat和Date。这些类设计不佳且早已过时,尤其是前者,尤其是出了名的麻烦。而是使用LocalDateTime、ZonedDateTime、DateTimeFormatter和来自java.time, the modern Java date and time API 的其他类。