【发布时间】:2018-10-10 13:28:05
【问题描述】:
我的应用程序从我的服务器获得了过去事件的日期和时间的响应。然而,我的服务器在另一个时区,这里的事情变得有点棘手。服务器时区是UTC +01:00,而我的是UTC +03:00。当我收到来自服务器的响应时,它们带有UTC +01:00 的时间戳。首先,我尝试以String 的形式接收日期,对其进行子串化,设置其时区,然后以适当的时间格式和时区返回它。 (我剪掉了 milisec 的最后 4 位,因为 DateFormat 否则无效。)
private String getFormattedDate(String date) {
DateFormat serverDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX");
DateFormat finalDateFormat = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
Calendar calendar = Calendar.getInstance();
TimeZone timeZone = calendar.getTimeZone();
serverDateFormat.setTimeZone(timeZone);
String cutoutDate = date.substring(0,23);
String cutoutZone = date.substring(27, date.length());
String dateInProperFormat = cutoutDate + cutoutZone;
Date finalDate = serverDateFormat.parse(dateInProperFormat);
return finalDateFormat.format(finalDate);
}
这会正确读取并转换所有内容:
服务器响应:
2018-04-30T07:26:55.1524511+01:00-> 子字符串响应:2018-04-30T07:26:55.152+01:00-> 最终格式:30-04-2018 09:26:55
但是,milisec 并不总是 7,所以当发生这种情况时,我收到了 Unparsable date 错误。这让我读到的日期不是String,而是Date。这将代码减少到只有 5 行:
private String getFormattedDate(Date date) {
SimpleDateFormat finalDateFormat = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
Calendar calendar = Calendar.getInstance();
TimeZone timeZone = calendar.getTimeZone();
finalDateFormat.setTimeZone(timeZone);
return finalDateFormat.format(date);
}
但是现在,时间总是在UTC +01:00。我尝试像这样获取时区:
TimeZone timeZone = TimeZone.getDefault();
但这并没有改变任何东西。我在第二种方法中到底做错了什么?如果需要,我准备分享更多我的代码。
【问题讨论】:
-
我一直不鼓励使用旧的
DateFormat、SimpleDateFormat、Calendar、TimeZone和Date类,因为它们设计得很糟糕而且经常很麻烦。在这种情况下更是如此,因为java.time, the modern Java date and time API, 更适合您的特定任务。我建议您将ThreeTenABP 添加到您的项目中,以便您可以使用OffsetDateTime、ZoneId和他们的朋友。java.time通常也更好用。
标签: android date datetime timezone