CCEPROD
CCEPROD

Reputation: 41

Reformat Timespan in C#

I have several strings that look like such:

where S represents seconds and M represents minutes

"MM Minutes and XX Seconds"
"MM Minutes"
"SS Seconds"
":SS"

How would I convert that to one of the following: String format "MM:SS" TimeSpan format

Any help appreciated! Thanks!

Upvotes: 3

Views: 188

Answers (2)

Chris Missal
Chris Missal

Reputation: 6123

You could use TempusReader. It's an open source project that I started to solve this exact problem (and to teach myself how to use Parsley).

Take a look at the examples on the GitHub page and see if it suits your needs. It will work for words like and in your first example. Like so:

TimeSpan x = new Time("2 days, 7 hours, 12 mins and 52 seconds") // 2.07:12:52

Also, a TempusReader.Time object can be implicitly cast to a TimeSpan.

Upvotes: 7

MethodMan
MethodMan

Reputation: 18843

you can do something like this as well if you want to test with DateTime.Now for example

DateTime currentTime = DateTime.Now;
TimeSpan duration = DateTime.Now.Subtract(currentTime);
MessageBox.Show(string.Format("{0:D2}:{1:D2}", duration.Minutes, duration.Seconds));

Upvotes: 0

Related Questions