Home >Java >javaTutorial >Why Does SimpleDateFormat('yyyy-MM-dd'T'HH:mm:ss'Z'') Show IST Instead of UTC, and How Can I Fix It?
SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'") Issue: Displaying IST Timezone
In Java, the SimpleDateFormat class allows you to format and parse dates according to a predefined pattern. When using the pattern "yyyy-MM-dd'T'HH:mm:ss'Z'", it is expected to represent a date and time in the UTC timezone. However, an issue arises when parsing such a string.
Consider the following code:
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'"); Date date = sdf.parse("2013-09-29T18:46:19Z"); System.out.println(date);
The expected output would be a date and time in the UTC timezone. However, many users have reported that it instead displays a date and time in the IST (Indian Standard Time) timezone. This leads to confusion and incorrect date handling.
Solution: Explicitly Set the Timezone
The issue arises because the SimpleDateFormat constructor only initializes the date pattern but does not set the timezone explicitly. To correct this, you need to set the timezone to UTC manually. Here's how you do it:
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'"); sdf.setTimeZone(TimeZone.getTimeZone("GMT")); Date date = sdf.parse("2013-09-29T18:46:19Z"); System.out.println(date);
By setting the timezone to GMT, the SimpleDateFormat parser will interpret the input string correctly and display the date and time in the expected UTC timezone.
The above is the detailed content of Why Does SimpleDateFormat('yyyy-MM-dd'T'HH:mm:ss'Z'') Show IST Instead of UTC, and How Can I Fix It?. For more information, please follow other related articles on the PHP Chinese website!