Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Comparing date strings with actual dates in Scala

Tags:

scala

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.

like image 689
Jack Avatar asked Dec 05 '12 19:12

Jack


2 Answers

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.

like image 175
virtualeyes Avatar answered Sep 21 '22 06:09

virtualeyes


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)
like image 44
Dominic Bou-Samra Avatar answered Sep 22 '22 06:09

Dominic Bou-Samra