Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 365
user1935160 Avatar asked Apr 03 '13 05:04

user1935160


2 Answers

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.

like image 50
Alexei Levenkov Avatar answered Oct 18 '22 17:10

Alexei Levenkov


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));
like image 37
Igby Largeman Avatar answered Oct 18 '22 17:10

Igby Largeman