41

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?

Sunny R Gupta
  • 5,026
  • 1
  • 31
  • 40
Majid
  • 13,853
  • 15
  • 77
  • 113

5 Answers5

60
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.

Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939
  • 5
    Be aware that this doesn't handle periods of greater than 24 hours (it loses the days part). – Matthew Watson Aug 28 '13 at 08:29
  • 3
    @MatthewWatson: Correct. I assumed OP's maximum is 24hours because of the title and what he has tried. He could include the days: `myTimeSpan.ToString(@"d\.hh\:mm")` – Tim Schmelter Aug 28 '13 at 08:36
14

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

Sriram Sakthivel
  • 72,067
  • 7
  • 111
  • 189
12
var result = string.Format("{0:D2}:{1:D2}",  myTimeSpan.Hours, myTimeSpan.Minutes);
Damith
  • 62,401
  • 13
  • 102
  • 153
  • 1
    This retains + and - in offset for time zone which is important. i.e. `15.10.2014 14:00:00 +02:00` representing 2pm local time in a timezone of +2 UTC. – GThree Dec 28 '18 at 15:58
4

From TimeSpan.ToString Method (String)

TimeSpan t = new TimeSpan(14, 53, 0);
Console.WriteLine(t.ToString(@"hh\:mm"));

As an alternative you can use String.Format like;

Console.WriteLine(String.Format("{0}:{1}", t.Hours, t.Minutes));

Remember, TimeSpan.ToString(String) overload only avaiable for .NET 4 or higher.

Soner Gönül
  • 97,193
  • 102
  • 206
  • 364
0

Try this will work 100% !!

myTimeSpan.ToString(@"dd\.hh\:mm");.
Bassam Alugili
  • 16,345
  • 7
  • 52
  • 70