Last active
August 29, 2015 14:01
-
-
Save nramsbottom/9f75effccae733fdc76c to your computer and use it in GitHub Desktop.
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
| 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