Created
September 26, 2015 03:03
-
-
Save ayush/5b8da92f145082413838 to your computer and use it in GitHub Desktop.
Parse a string "1 year, 2 months, 5 minutes" into DateTime
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
object PrettyTimeParser { | |
private val YEAR_REGEX = """(?<YEAR>\d+)\s*years?""".r | |
private val MONTH_REGEX = """(?<MONTH>\d+)\s*months?""".r | |
private val WEEK_REGEX = """(?<WEEK>\d+)\s*weeks?""".r | |
private val DAY_REGEX = """(?<DAY>\d+)\s*days?""".r | |
private val HOUR_REGEX = """(?<HOUR>\d+)\s*hours?""".r | |
private val MINUTE_REGEX = """(?<MINUTE>\d+)\s*minutes?""".r | |
private def lookup(regex: scala.util.matching.Regex, s: String): Int = { | |
Try(regex.findAllIn(s).toList.headOption.map(_.split(" ")).map(_(0).toInt)).getOrElse(None).getOrElse(0) | |
} | |
def parse(str: String): Option[DateTime] = { | |
val year = lookup(YEAR_REGEX, str) | |
val month = lookup(MONTH_REGEX, str) | |
val week = lookup(WEEK_REGEX, str) | |
val day = lookup(DAY_REGEX, str) | |
val hour = lookup(HOUR_REGEX, str) | |
val minute = lookup(MINUTE_REGEX, str) | |
val now = DateTime.now() | |
val dt = DateTime.now().plusYears(year) | |
.plusMonths(month) | |
.plusWeeks(week) | |
.plusDays(day) | |
.plusHours(hour) | |
.plusMinutes(minute) | |
if (dt.isAfter(now.getMillis)) Option(dt) else None | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment