Home >Java >javaTutorial >How to Convert a GMT Date/Time to a Specific Timezone (e.g., GMT 13) in Java?

How to Convert a GMT Date/Time to a Specific Timezone (e.g., GMT 13) in Java?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-11 03:39:10529browse

How to Convert a GMT Date/Time to a Specific Timezone (e.g., GMT 13) in Java?

Converting Date/Time for Specific Timezone

Question:

Converting a date and time in GMT to another timezone, such as GMT 13, requires setting the time, possibly modifying the initial timestamp's timezone, and formatting the time with the new timezone. However, attempting to set the time using milliseconds results in the use of the local machine's timezone.

Answer:

To achieve the desired result, the following steps are recommended:

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.TimeZone;

// Create a Calendar object and set the initial timestamp
Calendar calendar = Calendar.getInstance();
calendar.setTime(new Date(1317816735000L));

// Set the initial timezone to UTC (GMT)
calendar.setTimeZone(TimeZone.getTimeZone("UTC"));

// Create a SimpleDateFormat object with the desired date/time format
SimpleDateFormat sdf = new SimpleDateFormat("dd MMM yyyy HH:mm:ss z");

// Set the target timezone (GMT+13)
sdf.setTimeZone(TimeZone.getTimeZone("GMT+13"));

// Format the date/time with the new timezone
String newZealandTime = sdf.format(calendar.getTime());

// Print the converted date/time
System.out.println(newZealandTime);

By following these steps, you can successfully set the time, set the initial timestamp's timezone, format the time with the new timezone, and return a string with the converted date/time.

The above is the detailed content of How to Convert a GMT Date/Time to a Specific Timezone (e.g., GMT 13) in Java?. 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