21

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?

user1935160
  • 311
  • 1
  • 3
  • 8

2 Answers2

32

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.

Sergey
  • 1,608
  • 1
  • 27
  • 40
Alexei Levenkov
  • 98,904
  • 14
  • 127
  • 179
  • 3
    @user1935160: There's no need to separate the time of day from your DateTime instance. Just use `CurrentTime.ToString("HH:MM:ss.ffffff")`. The same goes for the Date portion. – Igby Largeman Apr 03 '13 at 05:15
  • Thank you very much for the detailed and helpful response! – user1935160 Apr 03 '13 at 05:15
  • And for anyone looking for a custom option to output something as trivial as 11:00 PM this custom code was the only way I found to do it: https://newbedev.com/how-to-convert-24-hour-format-timespan-to-12-hour-format-timespan – Guy Lowe Oct 08 '21 at 04:42
26

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));
Igby Largeman
  • 16,495
  • 3
  • 60
  • 86
  • 2
    Excellent. Took me two hours of reading on MSDN and pulling my hair out after testing a few permutations in code which got me nowhere, and only a few minutes of your expert time! Thanks again. – user1935160 Apr 03 '13 at 05:43