Timestamp string with milliseconds from a System.DateTime

You can easily convert a System.DateTime object into a string based on the current date and time by using the ToString() method of the DateTime object.  For instance:

DateTime d = DateTime.Now;
String s = d.ToString("yyyyMMdd-HHmmss");

Will produce a string with the value of “20091018-232013” assuming the date/time was 10/18/2009 11:20:13PM at the time the code was executed.

But did you know you can get the milliseconds of that System.DateTime object by using the “fff” format string:

DateTime d = DateTime.Now;
String s = d.ToString("yyyyMMdd-HHmmss.fff");

Will produce a string with the value of “20091018-232013.456” assuming the date/time was 10/18/2009 11:20:13.456PM at the time the code was executed.

I use this all the time when I need to append a timestamp to a log, a log filename, or just anything else that needs a quick way to turn a System.DateTime object into a string with milliseconds too.



3 Comments

Comments have been disabled for this content.