public static TimeSpan ParseDuration(this string strDuration)
{
var durationLiterals = new string[] { "w", "d", "h", "m", "s", "ms", "u" };
TimeSpan duration = TimeSpan.Zero;
if (strDuration != "0")
{
var indexes = durationLiterals.Select(s => strDuration.IndexOf(s, 0)).ToArray();
//handle only ms duration, and confusing with m and s with ms.
if (indexes[3] == indexes[5] && indexes[4] > indexes[5])
{
indexes[3] = indexes[5] = -1;
}
for (var index = 0; index < durationLiterals.Length; index++)
{
if (indexes[index] > -1)
{
try
{
int val = 0;
var len = index == 0 || indexes[index - 1] == -1 ? indexes[index] : indexes[index] - indexes[index - 1] - 1;
var start = index == 0 || indexes[index - 1] == -1 ? 0 : indexes[index - 1] + 1;
if (int.TryParse(strDuration.Substring(start, len), out val))
{
switch (durationLiterals[index])
{
case "w": duration += TimeSpan.FromDays(val * 7); break;
case "d": duration += TimeSpan.FromDays(val); break;
case "h": duration += TimeSpan.FromHours(val); break;
case "m": duration += TimeSpan.FromMinutes(val); break;
case "s": duration += TimeSpan.FromSeconds(val); break;
case "ms": duration += TimeSpan.FromMilliseconds(val); break;
case "u": duration += TimeSpan.FromMilliseconds(val / 1000); break;
}
}
}
catch (Exception)
{
throw;
}
}
}
}
else
{
duration = TimeSpan.MaxValue;
}
return duration;
}