Pavel Bernshtam
Pavel Bernshtam

Reputation: 4444

Scala: try different day formats

What is scala, elegant, functional way to parse a string using different date formats?

Let's say I have

val formats = Set(
  new SimpleDateFormat("YYYY-MM-dd"),
  new SimpleDateFormat("MM/DD/YYYY")
)

and I want to try parse a string using the first of those formats, which will parse successfully:

def parse(s:String): Option[Date] = {
  formats.map {??????????????}
}

Upvotes: 0

Views: 87

Answers (1)

Tzach Zohar
Tzach Zohar

Reputation: 37832

You can convert the list into a Stream (to make sure only the minimum number of parsing attempts are done), then use Try and collectFirst:

def parse(s:String): Option[Date] = {
  formats.toStream.map(f => Try(f.parse(s))).collectFirst {
    case Success(d) => d
  }
}

println(parse("2017-02-01"))  // Some(Sun Jan 01 00:00:00 IST 2017)
println(parse("02/01/2017"))  // Some(Sun Jan 01 00:00:00 IST 2017)
println(parse("23:00"))  // None

Upvotes: 1

Related Questions