Skip to content

Instantly share code, notes, and snippets.

@stuartd
Last active April 17, 2019 09:40
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 stuartd/5609c5c0a31bd4d13cd6e876480e592e to your computer and use it in GitHub Desktop.
Save stuartd/5609c5c0a31bd4d13cd6e876480e592e to your computer and use it in GitHub Desktop.
private TimeSpan ConvertDriveTimeStringToTime() {
if (string.IsNullOrEmpty(driveTime)) {
return TimeSpan.Zero;
}
// "1 day 4 hours", "4 hours 12 mins", "1 min"
var bits = driveTime.Split();
int value = 0;
TimeSpan result = TimeSpan.Zero;
foreach (string bit in bits) {
// If the value is already set, look for a unit
// otherwise parse the value and loop
if (value == 0 && int.TryParse(bit, out value)) {
continue;
}
switch (bit) {
case "day":
case "days":
result = result.Add(TimeSpan.FromDays(value));
break;
case "hour":
case "hours":
result = result.Add(TimeSpan.FromHours(value));
break;
case "min":
case "mins":
result = result.Add(TimeSpan.FromMinutes(value));
break;
default:
return TimeSpan.Zero;
}
// reset the number for the next value.
value = 0;
}
return result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment