Skip to content

Instantly share code, notes, and snippets.

@bradkovach
Created November 6, 2015 03:22
Show Gist options
  • Save bradkovach/3edf8157a535163a4689 to your computer and use it in GitHub Desktop.
Save bradkovach/3edf8157a535163a4689 to your computer and use it in GitHub Desktop.
/**
* Attempts to parse a string and return a strongly-typed object.
* Supports Date, datetime, datetime with timezone, double, long and string
* @param x a String to attempt to parse
* @return Option[Any] a null-friendly container for the result. Some[Any] when match succeeded. None when the match failed.
*/
def Cast(x: String): Option[Any] =
{
val long_months = "(January|February|March|April|May|June|July|August|September|October|November|December)"
val short_months = "(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)"
val two_digit = """(\d\d)"""
val four_digit = """(\d\d\d\d)"""
val space = """ """
val comma = ""","""
val dash = """-"""
val date = (four_digit + dash + two_digit + dash + two_digit).r
val date_nice_long = (long_months + """ (\d\d), (\d\d\d\d)""").r
val date_mla = ("""(\d\d) """ + long_months + """ (\d\d\d\d)""").r
val date_mla_short = ("""(\d\d) """ + short_months + """ (\d\d\d\d)""").r
val datetime = """(\d\d\d\d)-(\d\d)-(\d\d) (\d\d):(\d\d)""".r
val datetimezone = """(\d\d\d\d)-(\d\d)-(\d\d) (\d\d):(\d\d) ([A-Z]+)""".r
val double = """([-+]?[0-9]*\.[0-9]+|[0-9]+)""".r
val long = """([-+]?[0-9]*)""".r
val string = """(.*)""".r
x match {
case date(year, month, day) => Some(new SimpleDateFormat("yyyy-MM-dd").parse(x))
case datetime(year, month, day, hours, minutes) => Some(new SimpleDateFormat("yyyy-MM-dd HH:mm").parse(x))
case date_nice_long(month, day, year) => Some(new SimpleDateFormat("MMM dd, yyyy").parse(x))
case date_mla(day, month, year) => Some(new SimpleDateFormat("dd MMM yyyy").parse(x))
case date_mla_short(day, month, year) => Some(new SimpleDateFormat("dd MMM yyyy", Locale.US).parse(x))
case datetimezone(year, month, day, hours, minutes, tz) => Some(new SimpleDateFormat("yyyy-MM-dd HH:mm z").parse(x))
case long(i) if Long.MinValue <= i.toLong && i.toLong <= Long.MaxValue => Some(i.toLong)
case double(d) => Some(d.toDouble)
case string(string) => Some(string)
case _ => None
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment