I need to parse the string "26h44m3s" to TimeSpan in C#. I cannot find anything implemented in .NET that can handle it. So how do I accomplish it, and in clean way? And are there any existing nugets for this?
I am receiving the string from the "duration" property on Twitch API endpoint GetVideos.
You can use Noda Time for this, parsing as a Duration
. You could then convert it to a TimeSpan
- or you could use Noda Time everywhere and have a nicer experience :)
Sample code:
using System;
using NodaTime;
using NodaTime.Text;
class Program
{
static void Main()
{
string text = "26h44m3s";
var pattern = DurationPattern.CreateWithInvariantCulture("H'h'm'm's's'");
var duration = pattern.Parse(text).Value;
Console.WriteLine(duration);
var ts = duration.ToTimeSpan();
Console.WriteLine(ts);
}
}
If you have multiple patterns that need to match, you can create a composite pattern - although you'll need to list all the patterns explicitly. Here's an example of that:
using System;
using System.Linq;
using NodaTime;
using NodaTime.Text;
class Program
{
static void Main()
{
string[] formats =
{
"H'h'm'm's's'", "H'h'm'm'", "M'm's's'", "H'h'", "M'm'", "S's'"
};
var patterns = formats.Select(DurationPattern.CreateWithInvariantCulture);
var builder = new CompositePatternBuilder<Duration>();
foreach (var pattern in patterns)
{
// The second parameter is used to choose which pattern is
// used for formatting. Let's ignore it for now.
builder.Add(pattern, _ => true);
}
var composite = builder.Build();
string[] values = { "26h8m", "26h", "15s", "56m47s" };
foreach (var value in values)
{
Console.WriteLine(composite.Parse(value).Value);
}
}
}
See more on this question at Stackoverflow