【问题标题】:Joda Time: Convert UTC to localJoda 时间:将 UTC 转换为本地时间
【发布时间】:2011-05-01 16:35:09
【问题描述】:

我想将 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

【问题讨论】:

    标签: scala time local utc jodatime


    【解决方案1】:

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

    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
    

    【讨论】:

    • 完美。我把它改得更南一点,到墨尔本。
    猜你喜欢
    • 2018-07-27
    • 2014-07-18
    • 2021-02-04
    • 2010-09-15
    • 2019-04-30
    • 2017-03-20
    • 1970-01-01
    相关资源
    最近更新 更多