简体   繁体   English

在Scala中转换日期格式

[英]Convert date format in 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. 我正在尝试将以下格式的日期格式转换为:scala中的2011-09-30 00:00:00.0到20110930。 Does anyone have any ideas? 有人有什么想法吗?

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

Use something like this: 使用这样的东西:

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

You can probably use the Date Functions as mentioned in other answers. 您可能可以使用其他答案中提到的日期函数。 However if you are sure about the format to be 2011-09-30 00:00:00.0 但是,如果您确定格式为2011-09-30 00:00:00.0

A simple Map operation should be fine 一个简单的Map操作应该可以

val x = List("2011-09-30 00:00:00.0")
val output = x map (x => x.dropRight(11).replace("-",""))
> output: List[String] = List(20110930)

However this solution works If and Only If You can guarantee the input comes in the same format. 但是,此解决方案且仅当您可以保证输入格式相同时才有效

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM