乔达时间:将UTC转换为本地时间 [英] Joda Time: Convert UTC to local
本文介绍了乔达时间:将UTC转换为本地时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想将Joda Time UTC DateTime对象转换为本地时间.
I want to convert a Joda Time UTC DateTime object to local time.
这是一种行之有效的方法,似乎很奏效.但是必须有更好的方法.
Here's a laborious way to do it which seems to work. But there must be a better way.
这是没有周围声明的代码(在Scala中):
Here's the code (in Scala) without surrounding declarations:
val dtUTC = new DateTime("2010-10-28T04:00")
println("dtUTC = " + dtUTC)
val dtLocal = timestampLocal(dtUTC)
println("local = " + dtLocal)
def timestampLocal(dtUTC: DateTime): String = {
// This is a laborious way to convert from UTC to local. There must be a better way.
val instantUTC = dtUTC.getMillis
val localDateTimeZone = DateTimeZone.getDefault
val instantLocal = localDateTimeZone.convertUTCToLocal(instantUTC)
val dtLocal = new DateTime(instantLocal)
dtLocal.toString
}
这是输出:
dtUTC = 2010-10-28T04:00:00.000 + 11:00 本地= 2010-10-28T15:00:00.000 + 11:00
dtUTC = 2010-10-28T04:00:00.000+11:00 local = 2010-10-28T15:00:00.000+11:00
推荐答案
这是我在当前项目中使用的内容.
Here's what I use on a current project.
val marketCentreTime = timeInAnotherTimezone.withZone(DateTimeZone.forID("Australia/Melbourne"))
有帮助吗?
在当前TZ中,这需要花费一些时间,并转换为布里斯班时间.您可以使用相同的原理.
Here's something that takes a time in the current TZ and converts to Brisbane time. You can use the same principle.
Welcome to Scala version 2.8.0.final (Java HotSpot(TM) Client VM, Java 1.6.0_21).
Type in expressions to have them evaluated.
Type :help for more information.
scala> import org.joda.time._
import org.joda.time._
scala> def timestampBrisbane(date: DateTime): String = {
| date.withZone(DateTimeZone.forID("Australia/Brisbane")).toString
| }
timestampBrisbane: (date: org.joda.time.DateTime)String
scala> val date = new DateTime
date: org.joda.time.DateTime = 2010-10-28T16:22:03.481+11:00
scala> val dateBrisbane = timestampBrisbane(date)
dateBrisbane: String = 2010-10-28T15:22:03.481+10:00
这篇关于乔达时间:将UTC转换为本地时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文