Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How convert TimeSpan to 24 hours and minutes String?

I use this code for converting Timespan to String (for ex: 14:53) :

myTimeSpan.ToString("hh:mm"); 

but this error occurs:

Input string was not in a correct format

What is the proper way to do this?

like image 826
Majid Avatar asked Aug 28 '13 08:08

Majid


People also ask

What is the format of a TimeSpan?

"c" is the default TimeSpan format string; the TimeSpan. ToString() method formats a time interval value by using the "c" format string. TimeSpan also supports the "t" and "T" standard format strings, which are identical in behavior to the "c" standard format string.

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 TimeSpan C#?

C# TimeSpan struct represents a time interval that is difference between two times measured in number of days, hours, minutes, and seconds. C# TimeSpan is used to compare two C# DateTime objects to find the difference between two dates.


2 Answers

myTimeSpan.ToString(@"hh\:mm") 

Custom TimeSpan Format Strings

The custom TimeSpan format specifiers do not include placeholder separator symbols, such as the symbols that separate days from hours, hours from minutes, or seconds from fractional seconds. Instead, these symbols must be included in the custom format string as string literals. For example, "dd.hh\:mm" defines a period (.) as the separator between days and hours, and a colon (:) as the separator between hours and minutes.

like image 89
Tim Schmelter Avatar answered Sep 20 '22 19:09

Tim Schmelter


You need to use @"hh\:mm\" for TimeSpan. Timespan formatting is not exactly same as DateTime

myTimeSpan.ToString(@"hh\:mm"); 

Check out Msdn for more info

like image 25
Sriram Sakthivel Avatar answered Sep 20 '22 19:09

Sriram Sakthivel