JAVA:gmt 到本地时间的转换

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10153286/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 23:49:08  来源:igfitidea点击:

JAVA: gmt to local time conversion

javatimezone

提问by DJ'

I am developing a software in java.

我正在用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.

我从服务器获得了格林威治标准时间的时间戳。该软件可以在世界任何地方使用。现在我想获取运行软件的本地时区并将此 GMT 时间转换为本地时间。

Please tell me how to do this?

请告诉我如何做到这一点?

采纳答案by Raveesh Sharma

To get your local timezone :

要获取您的本地时区:

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

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

For the conversion:

对于转换:

Date TimeZone conversion in java?

java中的日期时区转换?

回答by Tomasz Nurkiewicz

Assuming your timestampis either a Dateor Number:

假设您timestamp是 aDateNumber

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:

如果您的时间戳以 a 形式给出String,则您首先必须对其进行解析。您会在 中找到大量带有自定义格式的示例SimpleDateFormat,一个带有内置格式的简单示例:

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));

回答by rsinha

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

假设服务器时间格式yyyy/MM/dd HH:mm:ss.SSS如下:

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();

回答by Wim Deblauwe

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

看看乔达时间。它具有您需要的所有日期相关功能