Skip to content

Instantly share code, notes, and snippets.

@ndrscodes
Created October 19, 2021 17:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ndrscodes/5b20c761180b3afb1d0a4346d6eb13ff to your computer and use it in GitHub Desktop.
Save ndrscodes/5b20c761180b3afb1d0a4346d6eb13ff to your computer and use it in GitHub Desktop.
O(n) way of parsing golang-formatted duration strings to TimeSpans in C#
/// <summary>
/// Highly performant method for parsing strings using the GoLang TimeSpan format (e.g. 23h59m59s)
/// If no time unit is specified, seconds will be assumed.
/// </summary>
/// <param name="str">the string to parse</param>
/// <returns>a TimeSpan representing the parsed value</returns>
public static TimeSpan ParseTimeSpan(string str)
{
if (str == null || string.IsNullOrWhiteSpace(str))
throw new ParseException("input may not be empty");
int? hours = null;
int? minutes = null;
int? seconds = null;
int tmp = 0;
bool valid = false;
for (int i = 0; i < str.Length; i++)
{
var current = str[i];
switch (current)
{
case 'h':
case 'H':
if (hours != null)
throw new ParseException("a value for hours has already been set: " + hours);
hours = tmp;
tmp = 0;
if (!valid)
throw new ParseException("empty values for hours are not allowed.");
valid = false;
break;
case 'm':
case 'M':
if (hours != null)
throw new ParseException("a value for minutes has already been set: " + minutes);
minutes = tmp;
tmp = 0;
if (!valid) throw new ParseException("empty values for minutes are not allowed.");
valid = false;
break;
case 's':
case 'S':
if (hours != null)
throw new ParseException("a value for seconds has already been set: " + seconds);
seconds = tmp;
tmp = 0;
if (!valid) throw new ParseException("empty values for seconds are not allowed.");
valid = false;
break;
default:
if (current < 48 || current > 57)
throw new ParseException("invalid character: " + current);
tmp = tmp * 10 + (current - 48);
valid = true;
break;
}
if (hours != null && minutes != null && seconds != null)
break;
}
if (tmp > 0)
if (seconds == null)
seconds = tmp;
else
throw new ParseException("input ending implies that seconds should be set, but they already have a value: " + seconds);
return new TimeSpan(hours ?? 0, minutes ?? 0, seconds ?? 0);
}
@ndrscodes
Copy link
Author

you may omit the 's' for seconds, eg. 3h4m2 instead of 3h4m2s.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment