I'm looking for a nice way to validate and then compare a date string passed from a REST service.
If I get 2012-12-25 (year-month-day) passed as a string, what would be an elegant way to confirm it's a valid date, and then to say that the date is in the future or in the past?
To work with dates in Scala, one can obviously use existing Java libraries. But, working with dates in Java has always been like serving the dark side, so I don't want to drag too much of that legacy into my current coding style. Looking at the Scala Dates example on langref.org, it feels that I'll be back to coding Java if I follow this style of programming.
JodaTime is fine, fine, fine, don't worry about the dark side, it doesn't exist (or at least not in this particular Java library).
// "20121205".to_date
class String2Date(ymd: String) {
def to_date = {
try{ Some(ymdFormat.parseDateTime(ymd)) }
catch { case e:Exception => None }
}
val ymdFormat = org.joda.time.format.DateTimeFormat.forPattern("yyyyMMdd")
}
@inline implicit final def string2Date(ymd: String) = new String2Date(ymd)
def dater(ymd: String) = {
val other = new JodaTime
ymd.to_date map{d=>
if(d.isBefore other) ...
else ...
} getOrElse("bad date format")
}
Can do virtually anything date/time related with JodaTime; it's absurd how good this library is: unequivocal thumbs up.
You can do this using the standard Java SimpleDateFormat library:
def parseDate(value: String) = {
try {
Some(new SimpleDateFormat("yyyy-MM-dd").parse(value))
} catch {
case e: Exception => None
}
}
And then used it like so:
parseDate("2012-125") // None
parseDate("2012-12-05") // Some(Wed Dec 05 00:00:00 EST 2012)
Then you can have a function for testing future dates:
def isFuture(value: Date) = value.after(new Date)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With