Java,如何将GMT时间更改为当地时间? [英] Java, How to change GMT time to local time?

查看:257
本文介绍了Java,如何将GMT时间更改为当地时间?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

服务器发送给我的时间如下:


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更好的日期/时间库。

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

请注意,只有在真正需要时才应该将字符串表达式转换为/。否则,根据您的使用情况使用最合适的类型 - 这是Joda Time真正闪耀的地方。


Server sends me time like this:

2012-06-08 17:00:00 +0100

I need to change it like HH:MM based on local time. For example this time is what time at Japan, India, US and etc.

How can I do this? Thanks

解决方案

Option 1: using java.util.Date/Calendar:

First you need to parse the value to a 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);

Option 2: using Joda Time

Joda Time is a much better date/time library for Java.

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

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆