Skip to content

Instantly share code, notes, and snippets.

@nramsbottom
Last active August 29, 2015 14:01
Show Gist options
  • Select an option

  • Save nramsbottom/9f75effccae733fdc76c to your computer and use it in GitHub Desktop.

Select an option

Save nramsbottom/9f75effccae733fdc76c to your computer and use it in GitHub Desktop.
public static TimeSpan GetTimePeriod(string str)
{
if (str == null)
throw new ArgumentNullException("str");
// Plain old regex: ([\+-]?)(\d+)([A-Za-z]+)?
Regex re = new Regex("(?<Operator>[+\\-]?)(?<Value>\\d+)(?<Unit>[A-Za-z]+)?", RegexOptions.IgnoreCase);
Match m = re.Match(str);
if (m.Success)
{
var op = m.Groups["Operator"].Value;
var unit = m.Groups["Unit"].Value.ToLower();
var value = int.Parse(m.Groups["Value"].Value);
var multiplier = op == "-" ? -1 : 1;
switch (unit)
{
case "d":
case "day":
case "days":
return new TimeSpan(value * multiplier, 0, 0, 0);
case "h":
case "hour":
case "hours":
return new TimeSpan(0, value * multiplier, 0, 0);
case "m":
case "minute":
case "minutes":
return new TimeSpan(0, 0, value * multiplier, 0);
default:
// assume hours
return new TimeSpan(0, value * multiplier, 0, 0);
}
}
return TimeSpan.Zero;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment