"scala/lift check if date is correctly formatted" Code Answer

2

simpledateformat is ugly and (more disturbingly) non-thread-safe. if you try to simultaneously use the same instance in 2 or more threads then expect things to blow up in a most unpleasant fashion.

jodatime is far nicer:

import org.joda.time.format._
val fmt = datetimeformat forpattern "dd/mm/yyyy"
val input = "12/05/2009"
val output = fmt parsedatetime input

if it throws an illegalargumentexception, then the date wasn't valid.

as i suspect you'll want to know the actual date if it was valid, you may want to return an option[datetime], with none if it was invalid.

def parsedate(input: string) = try {
  some(fmt parsedatetime input)
} catch {
  case e: illegalargumentexception => none
}

alternatively, use an either to capture the actual exception if formatting wasn't possible:

def parsedate(input: string) = try {
  right(fmt parsedatetime input)
} catch {
  case e: illegalargumentexception => left(e)
}

update

to then use the either, you have two main tactics:

map one of the two sides:

parsedate(input).left map (_.getmessage)
//will convert the either[illegalargumentexception, datetime]
//to an either[string, datetime]

fold it:

parsedate(input) fold (
  _ => s.error(
    "birthdate",
    "invalid date. please enter date in the form dd/mm/yyyy."),
  dt => successfunc(dt)
)

of course, the two can be composed:

parsedate(input).left map (_.getmessage) fold (
  errmsg => s.error("birthdate", errmsg), //if failure (left by convention)
  dt => successfunc(dt) //if success (right by convention)
)
By Bloodcast69 on May 9 2022
Only authorized users can answer the Search term. Please sign in first, or register a free account.