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 :)

# reitumetse said on 22 February, 2010 01:30 AM

i want to use timestamp so that it can show time and the day

# Business Online Marketing said on 29 November, 2010 08:30 AM

It may help others who are copying and pasting this code to know that the quote marks used are invalid characters.

Use: " "

Don't use: “ ”

# Jeff Widmer said on 29 November, 2010 08:36 AM

Thanks Business Online Marketing.  I corrected the double quote marks in the code snippet.

# sunil said on 07 December, 2010 03:42 AM

how can I pass timestamp values to stored procedures(Oracle). I uesed datetime but when I am comparing the timestamp value it's not matching.

basically what I am doing is, I pass a datetiem value to SP, which in turn compares this value with timestamp.

prolbem lies here. it's not macthing exaclty.

Please help...

Leave a Comment

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

Search

Go

This Blog

News

Syndication