Search code examples
scaladatetimedate-formatting

Parse timestamp into LocalDateTime Scala


I have a dataset for my User case class with the date of birth field. I want to put this data into my database, however, the date is represented in a form of the date stamp, so I do not know how to parse it using LocalDateTime. Here are the examples of the datestamps I have:

-631065600
885254400
48124800
-1007596800

And I tried to do something like this:

val formatter = DateTimeFormatter.ofPattern("n")

  val users = List(
    models.User(1, "[email protected]", "Роман", "Терленчан", "m", LocalDateTime.parse("885254400", formatter)),
    models.User(2, "[email protected]", "Артём", "Пенленный", "m", LocalDateTime.parse("48124800", formatter)),
    models.User(3, "[email protected]", "Борислав", "Фетленвич", "m", LocalDateTime.parse("-1007596800", formatter))
  )

But I've got such an exception:

java.time.DateTimeException: Unable to obtain LocalDate from TemporalAccessor: {NanoOfSecond=885254400},ISO of type java.time.format.Parsed

Solution

  • You can convert your variables from a timestamp to a LocalDateTime like this: LocalDateTime.ofInstant(Instant.ofEpochMilli(885254400), ZoneOffset.UTC)