在 Scala 中转换日期格式

Car*_*x3n 4 scala date

我正在尝试在 Scala 中将日期格式转换为如下所示:2011-09-30 00:00:00.0 到 20110930。有没有人有任何想法?

Yeh*_*kon 6

使用这样的东西:

import java.text.SimpleDateFormat

val inputFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.S")
val outputFormat = new SimpleDateFormat("ddMMyyyy")

val date = "2015-01-31 12:34:00.0"
val formattedDate = outputFormat.format(inputFormat.parse(date))

println(formattedDate) //20150131
Run Code Online (Sandbox Code Playgroud)


bot*_*aio 5

如果您只想将日期格式从字符串更改为字符串,您可以执行类似以下操作:

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
Run Code Online (Sandbox Code Playgroud)