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.



Published 18 October 2009 11:31 PM by Jeff Widmer
Filed under: ,

Comments

# Twitter Trackbacks for Timestamp string with milliseconds from a System.DateTime - Jeff Widmer's Blog [asp.net] on Topsy.com said on 19 October, 2009 12:08 AM

Pingback from  Twitter Trackbacks for                 Timestamp string with milliseconds from a System.DateTime - Jeff Widmer's Blog         [asp.net]        on Topsy.com

# jack.niu said on 26 October, 2009 03:24 AM

find how to define the milliseconds from here :)

Leave a Comment

(required) 
(required) 
(optional)
(required) 

Search

Go

This Blog

News

    Ads by Lake Quincy Media
    Ads by Lake Quincy Media

Recommended Blogs

Syndication