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
JAVA: gmt to local time conversion
提问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:
对于转换:
回答by Tomasz Nurkiewicz
Assuming your timestamp
is either a Date
or Number
:
假设您timestamp
是 aDate
或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:
如果您的时间戳以 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.SSS
this 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
看看乔达时间。它具有您需要的所有日期相关功能