Tushar Kesarwani
Tushar Kesarwani

Reputation: 596

How do i convert Datetime string to "yyyy-MM-dd'T'HH:mm:ss.SSSSSSSSSZ"

I have created the below function

def toUTCDate(dateString: String): Option[String] = {
    val parser = DateTimeFormatter.ofPattern("dd/MM/yyyy HH:mm:ss")
    val formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSSSSSSSZ")

    Try {
      ZonedDateTime.parse(dateString, parser)
    }.toOption
      .map(_.format(formatter))
  }

The problem with above code is it expects the input to have some timeZone but my input is a date-time string.

Sample input : "13/02/2017 16:05:45"
Expected output: "2017-02-13T16:05:45.000000000+01:00

Upvotes: 2

Views: 869

Answers (1)

SCouto
SCouto

Reputation: 7928

As you said, your problem is that you are using ZonedDateTime but your String has no time zone.

You can apply a default time Zone in the parser construction by importing ZoneId.

I've used UTC in the example below, but you can use GMT+1 or whichever zone you want

import java.time.ZoneId
val parser = DateTimeFormatter.ofPattern("dd/MM/yyyy HH:mm:ss").withZone(ZoneId.of("UTC"))
parser: java.time.format.DateTimeFormatter = Value(DayOfMonth,2)'/'Value(MonthOfYear,2)'/'Value(YearOfEra,4,19,EXCEEDS_PAD)' 'Value(HourOfDay,2)':'Value(MinuteOfHour,2)':'Value(SecondOfMinute,2)

scala> ZonedDateTime.parse(input, parser)
res12: java.time.ZonedDateTime = 2017-02-13T16:05:45Z[UTC]

scala> ZonedDateTime.parse(input, parser).format(formatter)
res13: String = 2017-02-13T16:05:45.000000000+0000

You can get the available ZonesId with the ZoneId.getAvailableZoneIds method

ZoneId.getAvailableZoneIds
res14: java.util.Set[String] = [Asia/Aden, America/Cuiaba, Etc/GMT+9, Etc/GMT+8, Africa/Nairobi, America/Marigot, Asia/Aqtau, Pacific/Kwajalein, America/El_Salvador, Asia/Pontianak, Africa/Cairo, Pacific/Pago_Pago, Africa/Mbabane, Asia/Kuching, Pacific/Honolulu, Pacific/Rarotonga, America/Guatemala, Australia/Hobart, Europe/London, America/Belize, America/Panama, Asia/Chungking, America/Managua, America/Indiana/Petersburg, Asia/Yerevan, Europe/Brussels, GMT, Europe/Warsaw, America/Chicago, Asia/Kashgar, Chile/Continental, Pacific/Yap, CET, Etc/GMT-1, Etc/GMT-0, Europe/Jersey, America/Tegucigalpa, Etc/GMT-5, Europe/Istanbul, America/Eirunepe, Etc/GMT-4, America/Miquelon, Etc/GMT-3, Europe/Luxembourg, Etc/GMT-2, Etc/GMT-9, America/Argentina/Catamarca, Etc/GMT-8, Etc/GMT-7, Etc/GMT-6, Euro...

So your code will result as follows:

def toUTCDate(dateString: String): Option[String] = {
    val parser = DateTimeFormatter.ofPattern("dd/MM/yyyy HH:mm:ss").withZone(ZoneId.of("UTC"))
    val formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSSSSSSSZ")

    Try {
      ZonedDateTime.parse(dateString, parser)
    }.toOption
      .map(_.format(formatter))
  }

Upvotes: 1

Related Questions