Search code examples
scalaplayframeworkjodatime

joda Datetime. How to SET timezone to the parsed DateTime?


I'm using Scala along with play framework. I want to parse the String with simple date and say it's in UTC. So if I have 2018-10-04 I want to get 2018-10-04T00:00:00.000Z

With this:

DateTime.parse("2018-10-04", DateTimeFormat.forPattern("yyyy-mm-dd")).withZone(DateTimeZone.UTC)

I keep getting 2018-10-03T22:00:00.000Z if I have +2 timezone. How to just say that it's already in UTC?


Solution

  • One way is to use LocalDatetime to initially ignore the timezone:

    scala> LocalDateTime.parse("2018-10-04", DateTimeFormat.forPattern("yyyy-MM-dd"))
    res11: org.joda.time.LocalDateTime = 2018-10-04T00:00:00.000
    

    then you can use toDateTime to make this UTC:

    scala> LocalDateTime.parse("2018-10-04", DateTimeFormat.forPattern("yyyy-MM-dd")).toDateTime(DateTimeZone.UTC)
    res12: org.joda.time.DateTime = 2018-10-04T00:00:00.000Z
    

    Also: You should use MM (month) rather than mm (minute).