-2

Please see this function that convert String into LocalDate:

  def getLocalDate(date: String): LocalDate = {

    LocalDate.parse(date, format.DateTimeFormatter.ofPattern("dd MMM, yyyy"))
  }

Usage:

val date = "01 Jan, 2010"
val localDate = getLocalDate(date)

So in case i have date with different format:

val date  = "01 Jan, 2010"

Is it possible to enable my function to support several formats instead of support only 1 ?

david hol
  • 1,272
  • 7
  • 22
  • 44
  • There's infinite formats. How does it know your format for this string? You must pass the format in. – waltersu Jul 27 '16 at 09:10

1 Answers1

2

Consider chaining calls to parse using scala.util.Try

def getLocalDate(date: String): LocalDate = {
  val pattern1 = DateTimeFormatter.ofPattern("dd MMM, yyyy")
  val pattern2 = DateTimeFormatter.ofPattern("dd MMM yyyy")
  val pattern3 = DateTimeFormatter.ISO_LOCAL_DATE

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

  result.get
}

parse throws DateTimeParseException when unable to parse a string. One can catch it and try again with another pattern.

After each step returned value is a Success or a Failure. In case of Success following recoveries are ignored.

Finally call get to return LocalDate contained in Success or rethrow exception caught by Failure.

Tomasz Błachut
  • 2,368
  • 1
  • 16
  • 23