-
-
Save mahizsas/7b05bd87b6ae99dacea7 to your computer and use it in GitHub Desktop.
Parse time from string
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
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