Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parse string to TimeSpan

Tags:

c#

timespan

I have some strings of xxh:yym format where xx is hours and yy is minutes like "05h:30m". What is an elegant way to convert a string of this type to TimeSpan?

like image 943
Serhat Ozgel Avatar asked Aug 25 '08 20:08

Serhat Ozgel


People also ask

How to Parse string to TimeSpan in c#?

Parse(String, IFormatProvider) Converts the string representation of a time interval to its TimeSpan equivalent by using the specified culture-specific format information.

How do I convert string to minutes?

Split the string into its component parts. Get the number of minutes from the conversion table. Multiply that by the number and that is the number of minutes. Convert that to whatever format you need for the display.

How do I convert DateTime to TimeSpan?

To convert a DateTime to a TimeSpan you should choose a base date/time - e.g. midnight of January 1st, 2000, and subtract it from your DateTime value (and add it when you want to convert back to DateTime ). If you simply want to convert a DateTime to a number you can use the Ticks property.

What is ParseExact C#?

ParseExact(String, String, IFormatProvider) Converts the specified string representation of a date and time to its DateTime equivalent using the specified format and culture-specific format information. The format of the string representation must match the specified format exactly.


2 Answers

This seems to work, though it is a bit hackish:

TimeSpan span;   if (TimeSpan.TryParse("05h:30m".Replace("m","").Replace("h",""), out span))             MessageBox.Show(span.ToString()); 
like image 59
Lars Mæhlum Avatar answered Sep 19 '22 23:09

Lars Mæhlum


DateTime.ParseExact or DateTime.TryParseExact lets you specify the exact format of the input. After you get the DateTime, you can grab the DateTime.TimeOfDay which is a TimeSpan.

In the absence of TimeSpan.TryParseExact, I think an 'elegant' solution is out of the mix.

@buyutec As you suspected, this method would not work if the time spans have more than 24 hours.

like image 39
John Sheehan Avatar answered Sep 21 '22 23:09

John Sheehan