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.
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.
DateTime.Now.TimeOfDay.ToString(@"hh\:mm\:ss")
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 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");
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");
TimeSpan
variable. Check this code: (new TimeSpan(10, 20, 0)).ToString("hh:mm")
–
Narra © 2022 - 2024 — McMap. All rights reserved.
TimeOfDay
. justDateTime.Now.ToString("hh:mm");
as a side note, it might be ambiguous if the time is beyond 12nn, better have thishh:mm tt
– RepetitiousDateTime.Now.TimeOfDay.ToString("hh\\:mm");
– Martsen