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?
(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.
In order to set the base time zone to GMT in Java, we use the setRawOffset(int offsetMillis) method. The java. util. TimeZone.
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.
To get your local timezone :
Calendar.getInstance().getTimeZone().getDisplayName()
For the conversion:
Date TimeZone conversion in java?
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));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With