Reputation: 2125
Running :
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;
}
}
I'm getting:
2017-07-01T07:58:23.000Z
2017-JUL-1 9:58:23
2017-6-1 9:58:23
Notice I'm getting hour = 9 while expected 7
Questions
Thanks !
Upvotes: 0
Views: 107
Reputation: 1405
Why this result
Due to this line:
ZonedDateTime zdt = ZonedDateTime.ofInstant(instant, ZoneId.systemDefault());
You're forcing your time zone over the one defined in the dateStr
, so the Calendar will use your time zone instead of the original one.
How to get the right result ?
Change your getFormatedDate
method to:
private Calendar getFormatedDate(final String dateStr) {
final ZonedDateTime zdt = ZonedDateTime.parse(dateStr);
return GregorianCalendar.from(zdt);
}
Upvotes: 1