正在运行:
public class test {
@Test
public void displayDate() {
SimpleDateFormat MONTH_FORMAT = new SimpleDateFormat("MMM", Locale.getDefault());
String testDateStr = "2017-07-01T07:58:23.000Z";
Calendar calendar = getFormatedDate(testDateStr);
int yearInt = calendar.get(Calendar.YEAR);
String monthStr = MONTH_FORMAT.format(calendar.getTime()).toUpperCase();
int monthInt = calendar.get(Calendar.MONTH);
int dayInt = calendar.get(Calendar.DAY_OF_MONTH);
int hour24 = calendar.get(Calendar.HOUR_OF_DAY);
int min = calendar.get(Calendar.MINUTE);
int sec = calendar.get(Calendar.SECOND);
System.out.println(testDateStr);
System.out.println(String.format("%s-%s-%s %s:%s:%s", yearInt, monthStr, dayInt, hour24, min, sec));
System.out.println(String.format("%s-%s-%s %s:%s:%s", yearInt, monthInt, dayInt, hour24, min, sec));
}
private Calendar getFormatedDate(String dateStr) {
Instant instant;
try {
instant = Instant.parse(dateStr);
} catch (DateTimeParseException e) {
e.printStackTrace();
return null;
}
ZonedDateTime zdt = ZonedDateTime.ofInstant(instant, ZoneId.systemDefault());
Calendar calendar = GregorianCalendar.from(zdt);
return calendar;
}
}
我得到:
2017-07-01T07:58:23.000Z
2017-JUL-1 9:58:23
2017-6-1 9:58:23
注意,我的小时数是9,而预期的是7
问题
谢谢!
答案 0 :(得分:1)
为什么会这样
由于此行:
ZonedDateTime zdt = ZonedDateTime.ofInstant(instant, ZoneId.systemDefault());
您将{strong>您的时区强制设置为dateStr
中定义的时区,因此日历将使用您的时区,而不是原来的时区。
如何获得正确的结果?
将您的getFormatedDate
方法更改为:
private Calendar getFormatedDate(final String dateStr) {
final ZonedDateTime zdt = ZonedDateTime.parse(dateStr);
return GregorianCalendar.from(zdt);
}