-3

I wrote the following regex to match date strings looking like:

2019/01/02 08:20:19

the regex is val reg = "([\\d]{4})/([\\d]{2})/([\\d]{2}) ([\\d]{2}).*.r"

The Scala function is:

val dateExtraction: String => Map[String, String] = {
  string: String => {
    string match {
      case reg(year, month, day, hour) =>
                 Map(YEAR -> year, MONTH -> month, DAY -> day, HOUR -> hour )
      case _  => Map(YEAR -> "", MONTH -> "", DAY -> "", HOUR -> "")
    }
  }
}
val YEAR = "YEAR"
val MONTH = "MONTH"
val DAY = "DAY"
val HOUR= "HOUR"

I want to get the year, month, day and hour from the regex. But the date above is not parsed as expected and I get a null result. Any idea how to fix this, please.

scalacode
  • 1,096
  • 1
  • 16
  • 38

1 Answers1

2

I would use java.time for such a problem, like:

  val input = "2019/01/02 08:20:19";
  val formatter = DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm:ss")
  val dt = LocalDateTime.from(formatter.parse(input)).atZone(ZoneId.systemDefault())

  dt.getYear() // 2019
  dt.getMonthValue() // 1
  dt.getDayOfMonth() // 2
  dt.getHour() // 8
pme
  • 14,156
  • 3
  • 52
  • 95