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

user1935160 picture user1935160 · Apr 3, 2013 · Viewed 34.7k times · Source

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?

Answer

Alexei Levenkov picture Alexei Levenkov · Apr 3, 2013

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.