TimeSpan.ToString(“hh:mm”) error [duplicate]

牧云@^-^@ 提交于 2019-12-17 20:17:19

问题


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.

回答1:


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

Documentation




回答2:


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");      



回答3:


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");


来源:https://stackoverflow.com/questions/29058212/timespan-tostringhhmm-error

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!