I am trying to change my timestamp from CST to EST but weirdly enough it is not working and I can quite figure out why.
String timestamp = "Wed Jul 07 10:35:10 CDT 2021";
String formattedTimestamp;
SimpleDateFormat sdfGFTime = new SimpleDateFormat("E MMM dd HH:mm:ss zzz yyyy", Locale.US);
TimeZone obj = TimeZone.getTimeZone("America/New_York");
Date date = null;
sdfGFTime.setTimeZone(obj);
date = sdfGFTime.parse(timestamp);
formattedTimestamp = sdfGFTime.format(date);
System.out.println(formattedTimestamp);
Output:
Wed Jul 07 10:35:10 CDT 2021
Expected:
Wed Jul 07 11:35:10 EST 2021
Any ideas on what I could be doing incorrent?
I recommend that you use java.time, the modern Java date and time API, for your date and time work. Let’s first define your formatter:
private static final DateTimeFormatter DTF
= DateTimeFormatter.ofPattern("EEE MMM dd HH:mm:ss zzz yyyy", Locale.ROOT);
Now, the conversion goes like this:
String timestamp = "Wed Jul 07 10:35:10 CDT 2021";
ZonedDateTime parsed = ZonedDateTime.parse(timestamp, DTF);
ZonedDateTime converted
= parsed.withZoneSameInstant(ZoneId.of("America/New_York"));
String formattedTimestamp = converted.format(DTF);
System.out.println(formattedTimestamp);
The output is not exactly what you said you expected, but close:
Wed Jul 07 11:35:10 EDT 2021
Also, in New York they use summertime (daylight saving time), so the time zone abbreviation for eastern time is given as EDT at this time of year, not EST.
This one is a bit tricky alright, but only one of an endless number of examples of SimpleDateFormat
not behaving the way we’d first expect. When you parse your string, the SimpleDateFormat
sets its time zone to the time zone it parsed from the string. You had set the time zone just before that, and your setting is just tacitly lost. So you get the Date
formatted back into the same time zone it came from. This is why I recommend that you never use SimpleDateFormat
.
Oracle tutorial: Date Time explaining how to use java.time.