7

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?

DJ'
  • 1,760
  • 1
  • 13
  • 26

4 Answers4

4

To get your local timezone :

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

For the conversion:

Date TimeZone conversion in java?

Community
  • 1
  • 1
Raveesh Sharma
  • 1,486
  • 5
  • 21
  • 38
4

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));
Tomasz Nurkiewicz
  • 334,321
  • 69
  • 703
  • 674
0

Have a look at Joda-Time. It has all the date related functions one needs

Wim Deblauwe
  • 25,113
  • 20
  • 133
  • 211
0

Assuming the server time in format yyyy/MM/dd HH:mm:ss.SSS this works:

String serverTime = "2017/12/06 21:04:07.406"; // GMT
ZonedDateTime gmtTime = LocalDateTime.parse(serverTime, DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm:ss.SSS")).atZone(ZoneId.of("GMT"));
LocalDateTime localTime = gmtTime.withZoneSameInstant(ZoneId.systemDefault()).toLocalDateTime();
rsinha
  • 683
  • 6
  • 9