我从json服务中检索一些值,并且检索到的日期时间值以UTC格式存储。 我已经尝试了很多示例代码将日期时间值转换为用户本地时区,但转换后我仍然获得相同的值。
这就是我实际上:(从其他帖子复制)
String sJsonDate = "2015-07-08T12:08:13.0625+00:00";
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
simpleDateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
try {
Date localDateTime = simpleDateFormat.parse(sJsonDate);
} catch (ParseException e) {
e.printStackTrace();
}
结果值(localDateTime)与原始值相同。 我在巴拉圭(GMT-4),结果值需要减去一小时差异,如下所示:(“2015-07-08 07:13:25”)(值存储在阿根廷)
请帮忙!
答案 0 :(得分:1)
我找到了解决方案,我们正在使用日光节省,所以我不得不将一小时的时间计算到最终的日期时间。
所以,我为别人分享了代码:
public Date getDateInTimeZone(Date currentDate, String timeZoneId) {
TimeZone timeZone = TimeZone.getTimeZone(timeZoneId);
Date localDateTime = new Date(currentDate.getTime() + timeZone.getOffset(currentDate.getTime()));
Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(localDateTime.getTime());
if (timeZone.useDaylightTime()) {
// time zone uses Daylight Saving
cal.add(Calendar.MILLISECOND, timeZone.getDSTSavings() * -1);// in milliseconds
}
return cal.getTime();
}
用法:
String sDate = "2015-07-08T12:08:13.0625+00:00";
try {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
Date theDate = simpleDateFormat.parse(sDate);
Date localDateTime = getDateInTimeZone(theDate, TimeZone.getDefault().getID());
} catch (ParseException e) {
e.printStackTrace();
}