SimpleDateFormatis ugly and (more disturbing) unrelated to the flow. If you try to use the same instance at the same time in 2 or more threads, then expect things to explode in the most unpleasant way.
JodaTime is much nicer:
import org.joda.time.format._
val fmt = DateTimeFormat forPattern "dd/MM/yyyy"
val input = "12/05/2009"
val output = fmt parseDateTime input
If he chose IllegalArgumentException, the date is invalid.
As I suspect, you will want to know the actual date, if it was valid, you can return Option[DateTime]with Noneif it was invalid.
def parseDate(input: String) = try {
Some(fmt parseDateTime input)
} catch {
case e: IllegalArgumentException => None
}
Alternatively, use Eitherto catch the actual exception if formatting is not possible:
def parseDate(input: String) = try {
Right(fmt parseDateTime input)
} catch {
case e: IllegalArgumentException => Left(e)
}
UPDATE
To use Either, you have two main tactics:
match one of two sides:
parseDate(input).left map (_.getMessage)
fold it:
parseDate(input) fold (
_ => S.error(
"birthdate",
"Invalid date. Please enter date in the form dd/mm/yyyy."),
dt => successFunc(dt)
)
Of course, they can be composed:
parseDate(input).left map (_.getMessage) fold (
errMsg => S.error("birthdate", errMsg),
dt => successFunc(dt)
)
source
share