java 如何将数据从一个时区转换为另一个时区?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7695859/
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
How to convert a data from 1 timezone to another timezone?
提问by user705414
Possible Duplicate:
Timezone conversion
可能重复:
时区转换
I have a date in UTC, how to convert it to other timezone?
我有一个 UTC 日期,如何将其转换为其他时区?
回答by Tomasz Nurkiewicz
java.util.Date
java.util.Date
Despite what the output of Date.toString()
suggests, Date
instances are nottimezone 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
尽管输出Date.toString()
表明,Date
实例不知道时区。它们只是代表一个时间点,与时区无关。因此,如果您有一个Date
实例,则无需再执行任何操作。如果您在一个时区有时间并且想知道其他时区的时间怎么办?你需要
java.util.Calendar
java.util.Calendar
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
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.
请注意,更改时区后,日期(时间点)并未更改。仅表示(此特定时区中的当前小时)。另请注意,11 月在那里很重要。如果我们突然将月份更改为 7 月,墨尔本的时间将更改为 16:00。那是因为东京不遵守夏令时,而墨尔本则遵守。
java.text.DateFormat
java.text.DateFormat
There is another catch in Java with time zones. When you are trying to format a date you need to specify time zone explicitly:
Java 中还有另一个时区问题。当您尝试格式化日期时,您需要明确指定时区:
DateFormat format = DateFormat.getTimeInstance
format.setTimeZone(TimeZone.getTimeZone("Europe/Moscow"))
Otherwise DateFormat
always uses current computer's time zone which is often inappropriate:
否则DateFormat
总是使用当前计算机的时区,这通常是不合适的:
format.format(cal.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.
由于format()
方法不允许Calendar
实例(即使它接受Object
作为参数 - 原文如此!)你必须调用Calendar.getTime()
- 它返回Date
. 如前所述 -Date
实例不知道时区,因此东京和墨尔本设置丢失。
回答by Mr.J4mes
You can try Joda-Time library. They have 2 functions called withZone() and withZoneRetainFields() to perform timezone calculations.
你可以试试Joda-Time 库。他们有 2 个称为 withZone() 和 withZoneRetainFields() 的函数来执行时区计算。