JAVA: gmt to local time conversion

2019-06-19 17:08发布

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?

标签: java timezone
4条回答
Juvenile、少年°
2楼-- · 2019-06-19 17:48

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));
查看更多
够拽才男人
3楼-- · 2019-06-19 17:53

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();
查看更多
叛逆
4楼-- · 2019-06-19 18:02

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

查看更多
太酷不给撩
5楼-- · 2019-06-19 18:03

To get your local timezone :

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

For the conversion:

Date TimeZone conversion in java?

查看更多
登录 后发表回答