Scala refactor string to Date code

Tag: mongodb , scala , date Author: dimwei2000 Date: 2013-10-21

I have an API that accepts a date as a string as a query parameter. For the most part, I expect my users to send an optional date parameter in the format of "yyyyMMdd" so an example would be 2013/10/12 for October 12th, 2013. I then search for records in a MongoDB and/or cache for certain data that matches said date. The code I have that turns the string into something that's sane in Scala is the following:

def parseDate(date: String): org.joda.time.DateTime = {
    val formatter = DateTimeFormat.forPattern("yyyyMMdd")  
    formatter.parseDateTime(date)
}

This works great. Now the issue I have is when the user does not submit a date, I want to default to today's date. This is where I need help. I don't have a great way of turning it into a string to pass to this method. I have code that looks like the following:

val gdate = params.getOrElse("gamedate", "0")
val date = gdate match {
   case gd:String => MyDateTimeHelper.parseDate(gd)
}

This is obviously wrong. I thought I could maybe do:

val gdate = params.getOrElse("gamedate", new DateTime)

But that also is not a solution (I was assuming it would just bypass the match since it's already a Date instance and not a string.

What's a decent way to solve this problem in Scala? I'm just jodatime for Scala to help me with all Date / Time type problems.

if you want datatime params to be ignored you can just add: case gd:DateTime => and let it just return gd and it fulfills the contract as its already being a date. or did i get you wrong?
Right now it does the right thing, it takes a string and turns it into a DateTime assuming the client passes an appropriately formatted date as "yyyyMMdd". But if it defaults to "0" as my code, I need a way to translate that into today's date as a string, today would be "20131106". I'd have to test if it defaulted to "0" and convert it to that value if that's the case and then turn it into a Date for further processing.
but you can use the "obviously wrong code" and modify your match statement?
Why don't you just format today-date to String? Something like val gdate = params.getOrElse("gamedate", formatter.format(new DateTime)). Then you everytime have to deal with the proper String.

Best Answer

You want Option and map:

val gdate:Option[String] = params.get("gamedate")
val date:Option[DateTime] = gdate map { MyDateTimeHelper.parseDate _ }
val dateOrDefault:DateTime = date.getOrElse(new DateTime)

comments:

Thanks, this was perfect. Exactly what I needed.