Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert date format in Scala

Tags:

date

scala

I am trying to convert a date format of that looks like this: 2011-09-30 00:00:00.0 to 20110930 in scala. Does anyone have any ideas?

like image 624
CaroV1x3n Avatar asked Dec 18 '22 01:12

CaroV1x3n


1 Answers

If all you want to do is to change date format from string to string all you may do something similar to:

def toSimpleDate(dateString: String): Option[String] = {
  val parser = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.S")
  val formatter = DateTimeFormatter.ofPattern("yyyyMMdd")

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

toSimpleDate("2011-09-30 00:00:00.0") // Some("20119030")
toSimpleDate("Meh") // None
like image 108
bottaio Avatar answered Jan 05 '23 16:01

bottaio