2010-10-28 9 views
6

Ich möchte ein Joda Time UTC DateTime-Objekt in lokale Zeit umwandeln.Joda-Zeit: UTC in Lokal umwandeln

Hier ist eine mühsame Art, es zu tun, die zu funktionieren scheint. Aber es muss einen besseren Weg geben.

Hier ist der Code (in Scala) ohne umgebende Erklärungen:

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 
    } 

Hier ist der Ausgang:

dtUTC = 2010-10-28T04: 00: 00.000 + 11: 00 local = 2010- 10-28T15: 00: 00.000 + 11: 00

Antwort

8

Hier ist, was ich bei einem aktuellen Projekt verwende.

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

Hilft das?

EDIT:

Hier ist etwas, das eine Zeit in der aktuellen TZ nimmt und wandelt in Brisbane Zeit. Sie können das gleiche Prinzip verwenden.

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 
+0

Perfekt. Ich passte es ein bisschen weiter südlich nach Melbourne an. – Koala3