将UTC日期从服务器转换为本地时间

时间:2016-06-11 11:17:38

标签: java android android-studio

我从服务器

获取此字符串为Date
2016-06-11T11:14:57.000Z

由于它是UTC,我想转换为我当地的时间。

SimpleDateFormat mFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
SimpleDateFormat endFormat = new SimpleDateFormat("hh:mm a");
mFormat.setTimeZone(TimeZone.getTimeZone("GMT+5:00"));
Date date = mFormat.parse(mBooking.startTime);

但是,日期转换为2:00AM

现在我不明白为什么11am转换为2:00AM

我做错了什么?

1 个答案:

答案 0 :(得分:3)

因为您没有为每个SimpleDateFormat正确设置时区,所以mFormat确实应设置为UTCendFormat设置为GMT + 5,此处是你应该做的:

SimpleDateFormat mFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
// Set UTC to my original date format as it is my input TimeZone
mFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
Date date = mFormat.parse("2016-06-11T11:14:57.000Z");
SimpleDateFormat endFormat = new SimpleDateFormat("hh:mm a");
// Set GMT + 5 to my target date format as it is my output TimeZone
endFormat.setTimeZone(TimeZone.getTimeZone("GMT+5:00"));

System.out.println(endFormat.format(date));

<强>输出:

04:14 PM
相关问题