How convert TimeSpan to 24 hours and minutes String?
Asked Answered
O

5

43

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?

Ossiferous answered 28/8, 2013 at 8:5 Comment(2)
Similar question answered here: #464142Redundancy
@AbhishekShetty; yes, however, the answers are pre .NET 4 (without TimeSpan.ToString).Lacteous
L
65
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.

Lacteous answered 28/8, 2013 at 8:9 Comment(2)
Be aware that this doesn't handle periods of greater than 24 hours (it loses the days part).Malvern
@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")Lacteous
T
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

Terrel answered 28/8, 2013 at 8:11 Comment(0)
G
12
var result = string.Format("{0:D2}:{1:D2}",  myTimeSpan.Hours, myTimeSpan.Minutes);
Godmother answered 28/8, 2013 at 8:12 Comment(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.Ironlike
R
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.

Rachael answered 28/8, 2013 at 8:10 Comment(0)
C
0

Try this will work 100% !!

myTimeSpan.ToString(@"dd\.hh\:mm");.
Chimney answered 28/8, 2013 at 8:9 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.