Skip to content

Instantly share code, notes, and snippets.

@mahizsas
Forked from hagbarddenstore/ParseTime.cs
Last active August 29, 2015 14:13
Show Gist options
  • Save mahizsas/7b05bd87b6ae99dacea7 to your computer and use it in GitHub Desktop.
Save mahizsas/7b05bd87b6ae99dacea7 to your computer and use it in GitHub Desktop.
Parse time from string
int ParseTime(string input)
{
var totalMinutes = 0;
input = Regex.Replace(input.ToLower(), "[^\\d|m|h]", string.Empty);
var hoursMatch = Regex.Match(input, "(?<Hours>\\d+)h");
if (hoursMatch.Success)
{
totalMinutes += int.Parse(hoursMatch.Groups["Hours"].Value) * 60;
}
var minutesMatch = Regex.Match(input, "(?<Minutes>\\d+)m");
if (minutesMatch.Success)
{
totalMinutes += int.Parse(minutesMatch.Groups["Minutes"].Value);
}
if ((!hoursMatch.Success && !minutesMatch.Success) || totalMinutes > (24 * 60))
{
throw new FormatException();
}
return totalMinutes;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment