C# 为什么 DateTime.Now.TimeOfDay.ToString("HH:mm:ss.ffffff") 抛出 FormatException?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15779246/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 17:55:15  来源:igfitidea点击:

Why does DateTime.Now.TimeOfDay.ToString("HH:mm:ss.ffffff") throw FormatException?

c#datetimeformatexception

提问by user1935160

I'm having a similar problem with FormatException being thrown. My code is simply:

我在抛出 FormatException 时遇到了类似的问题。我的代码很简单:

void Orders_OnSubmit()
{
   DateTime CurrentTime = DateTime.Now;
   rtbAdd( "Submitted on " + CurrentTime.Date.ToString("MM/dd/yyyy") + " at " + CurrentTime.TimeOfDay.ToString("HH:mm:ss.ffffff") );
}

void rtbAdd(String S)
{
   DefaultDelegate del = delegate()
   {
      rtb.AppendText(S + "\n");
   };
   this.Invoke(del);
}

What's wrong here? Is this a threading issue?

这里有什么问题?这是线程问题吗?

采纳答案by Igby Largeman

There's no need to explicitly access the Date and TimeOfDay properties of the DateTime instance. You can simplify your code like so:

无需显式访问 DateTime 实例的 Date 和 TimeOfDay 属性。您可以像这样简化代码:

rtbAdd(String.Format("Submitted on {0:MM/dd/yyyy} at {0:HH:mm:ss.ffffff}", DateTime.Now));

回答by Alexei Levenkov

TimeOfDayis of type TimeSpanand it has different formatting optionsthan DateTime. You also need to escape the colon (:)

TimeOfDay是类型的TimeSpan,它有不同的格式选项DateTime。您还需要转义冒号 ( :)

 currentTime.TimeOfDay.ToString("hh\:mm\:ss\.ffffff") 

Your sample tried to use the "HH"format which is defined for DateTime, but not for TimeSpan.

您的示例尝试使用"HH"定义DateTime的格式,而不是为TimeSpan