2d 10:00:00 to TimeSpan in C#

Viewed 265

It's possible somehow to convert something like:

2d 10:00:00

To TimeSpan in c#? There is already some function that converts it?

Some other examples could be:

30d 00:00:00
1m 3d 20:00:01
1y 2d 00:00:00

Or even Just:

3d
10d
3m
3y 10d
2 Answers

TimeSpan has very limited parsing abilities, and only goes up to days (not months or years). Another complexity is that some of these spans are context-dependent. A 3m span starting in Feb (which has a 28/29 and a 30-day month) is different than a 3m span starting in July (which has 2 31-day months).

So it depends on what you want to do with the span to determine the best way to parse. At some point you'll have to split the string by spaces and convert the Nm and Ny components to a number of days, adding the parsed time string component (hh:mm:ss) to that to generate a total TimeSpan.

Days, hours, minutes, and seconds are easy, as long as you've got a well-defined input format:

string input = "2d 10:00:00";
Timespan parsedTimespan = TimeSpan.ParseExact(input, @"d\d\ hh\:mm\:ss", CultureInfo.InvariantCulture)

As others have pointed out, Months, Years, etc. would be contextual. Technically days could be too, but in this case "days" always equates to 24 hours, regardless of your calendar.

To support other formats, like "2d", you'd probably have to write your own parsing code based on a spec that you come up with. Frameworks like Sprache can help if that gets very complicated.

Related