Home > Java > javaTutorial > How Do I Set a Specific Time Zone for a Java Date Object?

How Do I Set a Specific Time Zone for a Java Date Object?

Susan Sarandon
Release: 2024-12-22 07:54:09
Original
907 people have browsed it

How Do I Set a Specific Time Zone for a Java Date Object?

Modifying Time Zone of a Date Object in Java

Problem:

When parsing a java.util.Date from a string without explicit timezone information, the system's local time zone is automatically assigned to the resulting Date object. This may not be desirable in cases where a specific time zone needs to be specified.

Solution:

To set a custom time zone for a Date object, you can use the DateFormat class. Here's an example using SimpleDateFormat:

SimpleDateFormat isoFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
isoFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
Date date = isoFormat.parse("2010-05-23T09:01:02");
Copy after login

In this example:

  1. A SimpleDateFormat object (isoFormat) is created to parse the string into a Date object.
  2. The time zone of the SimpleDateFormat object is set to "UTC" using TimeZone.getTimeZone("UTC").
  3. The string "2010-05-23T09:01:02" is parsed into a Date object using isoFormat.parse().
  4. The Date object now has a time zone of UTC, regardless of the system's local time zone.

The above is the detailed content of How Do I Set a Specific Time Zone for a Java Date Object?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template