Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Joda Time: Convert UTC to local

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.

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
  }

Here's the output:

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

like image 769
Koala3 Avatar asked Oct 28 '10 04:10

Koala3


People also ask

Does Joda datetime have time zones?

An interval in Joda-Time represents an interval of time from one instant to another instant. Both instants are fully specified instants in the datetime continuum, complete with time zone.

Is Joda-Time deprecated?

So the short answer to your question is: YES (deprecated).

What is Joda-Time format?

Joda-Time provides a comprehensive formatting system. There are two layers: High level - pre-packaged constant formatters. Mid level - pattern-based, like SimpleDateFormat. Low level - builder.

What is Jodatime in java?

Joda-Time provides a quality replacement for the Java date and time classes. Joda-Time is the de facto standard date and time library for Java prior to Java SE 8. Users are now asked to migrate to java. time (JSR-310). Joda-Time is licensed under the business-friendly Apache 2.0 licence.


1 Answers

Here's what I use on a current project.

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

Does that help?

EDIT:

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
like image 142
Synesso Avatar answered Nov 15 '22 08:11

Synesso