I have a string 2017-07-31T01:01:00-07:00
and I am trying to parse it to date and in CST Timezone. I am getting different results when i parse this string using Date and Java 8 ZonedDateTime. I am not getting why this is happening and what I am doing wrong.
String dateStr = "2017-07-31T01:01:00-07:00";
LocalDateTime time = null;
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss-hh");
String[] dateArray = dateStr.split("-");
String[] timeZones = TimeZone
.getAvailableIDs(TimeZone.getTimeZone("GMT-" + dateArray[dateArray.length - 1]).getRawOffset());
format.setTimeZone(TimeZone.getTimeZone(timeZones[0]));
Date dateObj = null;
try {
dateObj = format.parse(dateStr);
} catch (ParseException e) {
e.printStackTrace();
}
time = dateObj.toInstant().atZone(TimeZone.getTimeZone("CST").toZoneId()).toLocalDateTime();
ZonedDateTime time2 = ZonedDateTime.parse(dateStr).toInstant().atZone(TimeZone.getTimeZone("CST").toZoneId());
System.out.println(time);
System.out.println(time2.toLocalDateTime());
See Question&Answers more detail:os