Scala how to get LocalDate by pattern
Asked Answered
C

1

5

I try to get LocaDate by format so i took this function that receive date and search for format to parse:

def getLocalDate(date: String): LocalDate = {

    val pattern1 = DateTimeFormatter.ofPattern("dd MMM, yyyy")
    val pattern2 = DateTimeFormatter.ofPattern("dd MMM yyyy")
    val pattern3 = DateTimeFormatter.ofPattern("yyyy-MMM-dd")
    val pattern4 = DateTimeFormatter.ofPattern("dd/MM/YYYY")
    val pattern5 = DateTimeFormatter.ISO_LOCAL_DATE

    val result = Try {
      LocalDate.parse(date, pattern1)
    } recover {
      case _ => LocalDate.parse(date, pattern2)
    } recover {
      case _ => LocalDate.parse(date, pattern3)
    } recover {
      case _ => LocalDate.parse(date, pattern4)
    } recover {
      case _ => LocalDate.parse(date, pattern5)
    }

    result.get
  }

Usage:

var s1 = "01/08/2010"
getLocalDate(s1)

But got an error:

java.time.format.DateTimeParseException: Text '01/08/2010' could not be parsed at index 0

And i don;t know why and what goes wrong.

Columbary answered 3/8, 2016 at 8:11 Comment(5)
I don't know scala but it seems you have to wrap each LocalDate.parse-call in a try block.Neighborly
I assume your example date "01/08/2010" should be matched by pattern 4, but it uses uppercase YYYY instead of yyyy.Howe
Same error with YYYY or yyyyColumbary
Are you sure? I just tested it using the yyyy pattern and it worked. If I use the YYYY pattern it throws.Enplane
pattern4 should be "dd/MM/yyyy"Maestro
S
8
import java.time.LocalDate
import java.time.format.DateTimeFormatter

import scala.util.Try

def getLocalDate(date: String): java.time.LocalDate = {
  val pattern1 = DateTimeFormatter.ofPattern("dd MMM, yyyy")
  val pattern2 = DateTimeFormatter.ofPattern("dd MMM yyyy")
  val pattern3 = DateTimeFormatter.ofPattern("yyyy-MMM-dd")
  val pattern4 = DateTimeFormatter.ofPattern("dd/MM/yyyy")
  val pattern5 = DateTimeFormatter.ISO_LOCAL_DATE

  val result = Try {
    LocalDate.parse(date, pattern1)
  } recover {
    case _ => LocalDate.parse(date, pattern2)
  } recover {
    case _ => LocalDate.parse(date, pattern3)
  } recover {
    case _ => LocalDate.parse(date, pattern4)
  } recover {
    case _ => LocalDate.parse(date, pattern5)
  }

  result.get
}
var s1 = "01/08/2010"
getLocalDate(s1)

This works nicely in REPL (Scala 2.11.8, Java 1.8).

Your mistake was to include "YYYY" in last pattern instead of "yyyy". Also, take a look at package nscala-time. Maybe it will provide better bindings for your applications.

Savoury answered 3/8, 2016 at 8:45 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.