gpt4 book ai didi

scala - Joda Time : Convert UTC to local

转载 作者:行者123 更新时间:2023-12-04 14:35:20 27 4
gpt4 key购买 nike

我想将 Joda Time UTC DateTime 对象转换为本地时间。

这是一种费力的方法,似乎有效。但必须有更好的方法。

这是没有周围声明的代码(在 Scala 中):

    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

最佳答案

这是我在当前项目中使用的内容。

val marketCentreTime = timeInAnotherTimezone.withZone(DateTimeZone.forID("Australia/Melbourne"))

这有帮助吗?

编辑:

这是在当前 TZ 中需要时间并转换为布里斯类时间的内容。您可以使用相同的原理。
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

关于scala - Joda Time : Convert UTC to local,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4039863/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com