You should not parse the timezone offset yourself. Just use the X
pattern:
new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssX")
You should not use timezone CST
, since that is ambiguous (Central Standard Time, China Standard Time, Cuba Standard Time). Use America/Chicago
(I assume that's what you meant).
So, to parse the date string with old and new APIs:
String dateStr = "2017-07-31T01:01:00-07:00";
// Using Date
SimpleDateFormat parseFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssX");
Date date = parseFormat.parse(dateStr);
SimpleDateFormat printFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm");
printFormat.setTimeZone(TimeZone.getTimeZone("America/Chicago"));
System.out.println(printFormat.format(date));
// Using ZonedDateTime
ZonedDateTime zonedDateTime = ZonedDateTime.parse(dateStr);
zonedDateTime = zonedDateTime.withZoneSameInstant(ZoneId.of("America/Chicago"));
System.out.println(zonedDateTime.toLocalDateTime());
Output
2017-07-31T03:01
2017-07-31T03:01
If you want to see the time zone, you can do this:
String dateStr = "2017-07-31T01:01:00-07:00";
// Using Date
SimpleDateFormat parseFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssX");
Date date = parseFormat.parse(dateStr);
SimpleDateFormat printFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm XXX z");
printFormat.setTimeZone(TimeZone.getTimeZone("America/Chicago"));
System.out.println(printFormat.format(date));
// Using ZonedDateTime
ZonedDateTime zonedDateTime = ZonedDateTime.parse(dateStr);
DateTimeFormatter printFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm XXX z")
.withZone(ZoneId.of("America/Chicago"));
System.out.println(zonedDateTime.format(printFormatter));
Output
2017-07-31T03:01 -05:00 CDT
2017-07-31T03:01 -05:00 CDT
Note how the first example changes the ZonedDateTime
timezone, converts it to a LocalDateTime
, then prints that without a formatter, while in the second example the DateTimeFormatter
is setup to format the value in a specific timezone, similar to how the SimpleDateFormat
is doing it. Just different ways of accomplishing the same result.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…