如何将数据从1个时区转换为另一个时区? [英] How to convert a data from 1 timezone to another timezone?

查看:140
本文介绍了如何将数据从1个时区转换为另一个时区?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

时区转换

我有一个UTC日期,如何将其转换为其他时区?

I have a date in UTC, how to convert it to other timezone?

推荐答案

java.util.Date



尽管有什么输出 Date.toString()建议,日期实例时区感知。它们只是代表一个时间点,与时区无关。因此,如果您有 Date 实例,则无需执行任何操作。如果你在一个时区有时间并想知道其他时区的时间是什么怎么办?你需要

java.util.Date

Despite what the output of Date.toString() suggests, Date instances are not timezone aware. They simply represent a point in time, irrespective to the timezone. So if you have a Date instance, there is nothing more you need to do. And what if you have time in one time zone and you want to know what is the time in other time zone? You need

Calendar cal = new GregorianCalendar(TimeZone.getTimeZone("Asia/Tokyo"))
cal.set(Calendar.HOUR_OF_DAY, 15)  //15:00 in Tokyo
cal.set(Calendar.MONTH, Calendar.NOVEMBER)

cal.setTimeZone(TimeZone.getTimeZone("Australia/Melbourne"))
cal.get(Calendar.HOUR_OF_DAY)  //17:00 in Melbourne

请注意,更改时区后日期(时间点)没有改变。仅表示(此特定时区的当前小时)。还要注意11月在那里很重要。如果我们将月份改为7月,那么墨尔本的小时将变为16:00。那是因为东京不遵守DST,而墨尔本则这样做。

Note that after changing the time zone the date (point in time) didn't changed. Only the representation (current hour in this particular time zone). Also note that November is important there. If we change the month to July suddenly the hour in Melbourne changes to 16:00. That's because Tokyo does not observe DST, while Melbourne does.

还有另一个使用时区捕获Java。当您尝试格式化日期时,需要明确指定时区:

There is another catch in Java with time zones. When you are trying to format a date you need to specify time zone explicitly:

DateFormat format = DateFormat.getTimeInstance
format.setTimeZone(TimeZone.getTimeZone("Europe/Moscow"))

否则 DateFormat 总是使用当前计算机的时区,这通常是不合适的:

Otherwise DateFormat always uses current computer's time zone which is often inappropriate:

format.format(cal.getTime())

由于 format()方法不允许 Calendar 实例(即使它接受 Object 作为参数 - sic!)你必须调用 Calendar.getTime() - 返回日期。正如之前所说 - 日期实例不知道时区,因此东京和墨尔本的设置都会丢失。

Since format() method does not allow Calendar instances (even though it accepts Object as a parameter - sic!) you have to call Calendar.getTime() - which returns Date. And as being said previously - Date instances are not aware of time zones, hence the Tokyo and Melbourne settings are lost.

这篇关于如何将数据从1个时区转换为另一个时区?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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