Search code examples
scalalocaldate

Scala generic format convert determain


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 ?


Solution

  • 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.