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.
Mohamad Shiralizadeh
  • 8,329
  • 6
  • 58
  • 93

3 Answers3

82
DateTime.Now.TimeOfDay.ToString(@"hh\:mm\:ss")

Documentation

Ravi M Patel
  • 2,905
  • 2
  • 23
  • 32
  • 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. – Beauty Aug 29 '23 at 16:27
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");      
Michaël Hompus
  • 3,349
  • 24
  • 35
  • 3
    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. – Bob Jan 30 '20 at 20:01
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");
dotNET
  • 33,414
  • 24
  • 162
  • 251