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

落爺英雄遲暮 提交于 2019-12-03 23:51:18

问题


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

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?


回答1:


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

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



回答2:


TimeOfDay is of type TimeSpan and it has different formatting options than DateTime. You also need to escape the colon (:)

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

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



来源:https://stackoverflow.com/questions/15779246/why-does-datetime-now-timeofday-tostringhhmmss-ffffff-throw-formatexceptio

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