Home >Java >javaTutorial >How to Specify a Time Zone for a java.util.Date Object?
Setting Time Zone of a java.util.Date
When parsing a java.util.Date from a string, the default local time zone is often applied. However, this may not be the desired time zone for the date. This article explores how to specify a specific time zone for a java.util.Date.
Utilizing DateFormat
To set the time zone of a Date object effectively, the DateFormat class can be employed. This class provides the ability to parse and format dates according to different time zones. Here's an example demonstrating its usage:
import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Date; import java.util.TimeZone; public class SetTimezoneOfDate { public static void main(String[] args) throws Exception { // Create a date object from a string String dateString = "2010-05-23T09:01:02"; // Initialize a SimpleDateFormat object SimpleDateFormat isoFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss"); // Set the desired time zone (UTC in this example) isoFormat.setTimeZone(TimeZone.getTimeZone("UTC")); // Parse the string into a Date object Date date = isoFormat.parse(dateString); // Display the parsed date with the specified time zone System.out.println("Parsed Date: " + date); } }
In this example, the SimpleDateFormat is configured to use the "UTC" time zone before parsing the date string. This ensures that the parsed Date object accurately reflects the specified time zone. The output will display the parsed date with the UTC time zone applied.
The above is the detailed content of How to Specify a Time Zone for a java.util.Date Object?. For more information, please follow other related articles on the PHP Chinese website!