Reputation: 3379
I have a time span string like this: 20 min 49 sec
I would like to parse it TimeSpan
instance, however I'm having bad time with it.
From the docs, it states that days and hours properties have to be set, but in my case I don't have them and I'd like to know if it's possible to make create such format where I can omit those values.
Upvotes: 1
Views: 741
Reputation: 3813
Taken from https://learn.microsoft.com/en-us/dotnet/api/system.timespan.parseexact?view=net-8.0
var intervalString = "17:14:48.153";
var format = @"h\:mm\:ss\.fff";
var result = TimeSpan.ParseExact(intervalString, format);
More examples on their site.
Upvotes: 0
Reputation: 391336
To parse that exact string, you'd use this expression:
TimeSpan.ParseExact(input, @"%m' min '%s' sec'", CultureInfo.InvariantCulture)
Basically, you treat every text other than where the numbers are as literal delimiters, specified using the 'xxx'
syntax.
If you think you might need to handle both min
and mins
as well as sec
and secs
, you need to use the overload with multiple formats:
string[] formats = new[]
{
"%m' min '%s' sec'",
"%m' mins '%s' sec'",
"%m' min '%s' secs'",
"%m' mins '%s' secs'"
};
TimeSpan.ParseExact(input, formats, CultureInfo.InvariantCulture)
And contrary to what you think the documentation states, you don't have to specify days or hours at all, this is perfectly legal:
TimeSpan ts = TimeSpan.FromMilliseconds(45);
Upvotes: 3