I have a string ("2021-11-05T22:33:10Z") which represents UTC time. I need to get the equivalent cst time("2021-11-05T16:33:10Z"). i have the below code but it returns time as 2021-11-05T17:33:10Z. Why is an hour getting add to the final time?
public class MyClass { public static void main(String args[]) throws ParseException { String busDate = "2021-11-05T22:33:10Z"; SimpleDateFormat currentFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'"); currentFormat.setTimeZone(TimeZone.getTimeZone("UTC")); Date utcTime = currentFormat.parse(busDate); System.out.println(utcTime); //Fri Nov 05 22:33:10 GMT 2021 SimpleDateFormat updateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'"); updateFormat.setTimeZone(TimeZone.getTimeZone("America/Chicago")); String formattedDateTime = updateFormat.format(utcTime); System.out.println(formattedDateTime); //2021-11-05T17:33:10Z }
} 4 1 Answer
tl;dr
You asked:
Why is an hour getting add to the final time?
Your expectation is incorrect. DST was in effect on the 5th in that zone.
2021-11-05T22:33:10Z = 2021-11-05T17:33:10-05:00[America/Chicago]
Use only java.time
You are using terrible date-time classes that were years ago supplanted by the modern java.time classes defined in JSR 310.
Moment in UTC
Instant instant = Instant.parse( "2021-11-05T22:33:10Z" ) ;instant.toString(): 2021-11-05T22:33:10Z
Adjust from UTC to a time zone
ZoneId z = ZoneId.of( "America/Chicago" ) ;
ZonedDateTime zdt = instant.atZone( z ) ;zdt.toString(): 2021-11-05T17:33:10-05:00[America/Chicago]
Note that your expectation of 2021-11-05T16:33:10Z as result is incorrect. Chicago time was five hours behind UTC on November 5, under Daylight Saving Time (DST), not six hours. DST ended on November 7, 2021. For the rest of November, Chicago time is six hours behind UTC.
See this code run live at IdeOne.com.
Real time zone names
There is no such time zone as cst or CST. To some people that means Central Standard Time, to many more people that means China Standard Time. Use these 2-4 letter pseudo-zones only for localizing in presentation to the user, never for data exchange. Behind the scenes, use only real time zones in format of Continent/Region.
For data-exchange, use only ISO 8601 standard formats.
1