TimeSpan.ToString("hh:mm") error [duplicate]
Asked Answered
N

3

48

Why I got an error when I want to get the string of a TimeSpan with a custom format.

DateTime.Now.TimeOfDay.ToString("hh:mm");
// Error: Input string was not in a correct format.
Narra answered 15/3, 2015 at 7:19 Comment(3)
remove TimeOfDay. justDateTime.Now.ToString("hh:mm"); as a side note, it might be ambiguous if the time is beyond 12nn, better have this hh:mm ttRepetitious
that was an example using DateTime. I have a TimeSpan variable. Check this code: (new TimeSpan(10, 20, 0)).ToString("hh:mm")Narra
DateTime.Now.TimeOfDay.ToString("hh\\:mm");Martsen
B
83
DateTime.Now.TimeOfDay.ToString(@"hh\:mm\:ss")

Documentation

Bevan answered 15/3, 2015 at 7:29 Comment(1)
Also regard to use hh instead of HH for hours, because HH will cause a FormatException. It's a pitfall, because for DateTime the HH is used for the 24 hours format.Scrape
R
27

According to MSDN TimeOfDay is a TimeSpan. And in the examples of TimeSpan.ToString you see that the : needs to be escaped.

hh\:mm\:ss: 03:00:00

This is also explained on Microsoft's page 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.

So try:

DateTime.Now.TimeOfDay.ToString("hh\\:mm");      
Rentsch answered 15/3, 2015 at 7:27 Comment(1)
Oh my god, this example made my day. I just wasted 2 hours reading the docs ignoring the fact that they (breaking ALL world standards as usual) uses backslashes in a format string.Halfon
K
1

Do not use TimeOfDay. Directly do ToString() on DateTime.Now:

DateTime.Now.ToString("hh:mm");

TimeOfDay is a TimeSpan. The docs clearly state this about TimeSpan.ToString(string format) overload:

The format parameter can be any valid standard or custom format specifier for TimeSpan values. If format is equal to String.Empty or is null, the return value of the current TimeSpan object is formatted with the common format specifier ("c"). If format is any other value, the method throws a FormatException.

If you must do it using a TimeSpan variable, you can simply add it to a DateTime variable that has its time part set to zero, and then use its ToString():

DateTime.Today.Add(YourTimeSpanVariable).ToString("hh:mm");
Kind answered 15/3, 2015 at 7:21 Comment(1)
that was an example using DateTime. I have a TimeSpan variable. Check this code: (new TimeSpan(10, 20, 0)).ToString("hh:mm")Narra

© 2022 - 2024 — McMap. All rights reserved.