Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JAVA: gmt to local time conversion

Tags:

java

timezone

I am developing a software in java.

I get a timestamp in GMT from a server. The software can be used anywhere in the world. Now I want to get the local time zone where the software is running and convert this GMT time to the local time.

Please tell me how to do this?

like image 546
DJ' Avatar asked Apr 14 '12 11:04

DJ'


People also ask

How do I convert GMT to local time?

(GMT-5:00) Eastern Time (US & Canada)Add the local time offset to the UTC time. For example, if your local time offset is -5:00, and if the UTC time is shown as 11:00, add -5 to 11. The time setting when adjusted for offset is 06:00 (6:00 A.M.). Note The date also follows UTC format.

How do I change timezone to GMT in Java?

In order to set the base time zone to GMT in Java, we use the setRawOffset(int offsetMillis) method. The java. util. TimeZone.

How to Convert TimeZone Java?

To convert a ZonedDateTime instance from one timezone to another, follow the two steps: Create ZonedDateTime in 1st timezone. You may already have it in your application. Convert the first ZonedDateTime in second timezone using withZoneSameInstant() method.


2 Answers

To get your local timezone :

Calendar.getInstance().getTimeZone().getDisplayName()

For the conversion:

Date TimeZone conversion in java?

like image 189
Raveesh Sharma Avatar answered Sep 22 '22 13:09

Raveesh Sharma


Assuming your timestamp is either a Date or Number:

final DateFormat formatter = DateFormat.getDateTimeInstance();
formatter.setTimeZone(TimeZone.getTimeZone("America/New_York"));
System.out.println(formatter.format(timestamp));

If your timestamp is given as a String, you first have to parse it. You'll find plenty of examples with custom format in SimpleDateFormat, a simple example with built-in format:

final DateFormat formatter = DateFormat.getDateTimeInstance();
formatter.setTimeZone(TimeZone.getTimeZone("GMT"));
final Date timezone = formatter.parse("2012-04-14 14:23:34");
formatter.setTimeZone(TimeZone.getTimeZone("America/New_York"));
System.out.println(formatter.format(timezone));
like image 34
Tomasz Nurkiewicz Avatar answered Sep 21 '22 13:09

Tomasz Nurkiewicz