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?

Why Does SimpleDateFormat('yyyy-MM-dd'T'HH:mm:ss'Z'') Show IST Instead of UTC, and How Can I Fix It?

Susan Sarandon
Susan SarandonOriginal
2024-12-13 20:03:13443browse

Why Does SimpleDateFormat(

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn