Java,如何将GMT时间更改为当地时间? [英] Java, How to change GMT time to local time?
问题描述
服务器发送给我的时间如下:
2012-06-08 17:00:00 +0100
我需要根据当地时间将其更改为 HH:MM
。例如,这个时间是在日本,印度,美国等什么时间。
我该怎么做?谢谢
选项1:使用 java.util.Date
/ Calendar
:
首先,您需要将值分解为日期
,然后按照您感兴趣的格式和时区
重新格式化它:
SimpleDateFormat inputFormat = new SimpleDateFormat(yyyy-MM-dd HH:mm:ss z,
Locale.US);
日期日期= inputFormat.parse(inputText);
//可能使用默认的语言环境。这将使用当地的时区。
SimpleDateFormat outputFormat = new SimpleDateFormat(HH:mm,Locale.US);
String outputText = outputFormat.format(date);
选项2:使用Joda时间 Joda Time 是Java更好的日期/时间库。 请注意,只有在真正需要时才应该将字符串表达式转换为/。否则,根据您的使用情况使用最合适的类型 - 这是Joda Time真正闪耀的地方。 Server sends me time like this: 2012-06-08 17:00:00 +0100 I need to change it like How can I do this? Thanks Option 1: using First you need to parse the value to a Option 2: using Joda Time Joda Time is a much better date/time library for Java. Note that you should only convert to/from string representations when you really need to. Otherwise, use the most appropriate type based on your usage - this is where Joda Time really shines. 这篇关于Java,如何将GMT时间更改为当地时间?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
DateTimeFormatter inputFormatter = DateTimeFormat
.forPattern(yyyy-MM-dd HH:mm:ss Z)
.withLocale(Locale.US);
DateTime parsed = inputFormatter.parseDateTime(inputText);
DateTimeFormatter outputFormatter = DateTimeFormat
.forPattern(HH:mm)
.withLocale(Locale.US)
.withZone(DateTimeZone.getDefault());
String outputText = outputFormatter.print(parsed);
HH:MM
based on local time. For example this time is what time at Japan, India, US and etc.java.util.Date
/Calendar
:Date
, then reformat it in the format and time zone
you're interested in:SimpleDateFormat inputFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss z",
Locale.US);
Date date = inputFormat.parse(inputText);
// Potentially use the default locale. This will use the local time zone already.
SimpleDateFormat outputFormat = new SimpleDateFormat("HH:mm", Locale.US);
String outputText = outputFormat.format(date);
DateTimeFormatter inputFormatter = DateTimeFormat
.forPattern("yyyy-MM-dd HH:mm:ss Z")
.withLocale(Locale.US);
DateTime parsed = inputFormatter.parseDateTime(inputText);
DateTimeFormatter outputFormatter = DateTimeFormat
.forPattern("HH:mm")
.withLocale(Locale.US)
.withZone(DateTimeZone.getDefault());
String outputText = outputFormatter.print(parsed);