Get DateTime.Now with milliseconds precision
Solution 1:
How can I exactly construct a time stamp of actual time with milliseconds precision?
I suspect you mean millisecond accuracy. DateTime
has a lot of precision, but is fairly coarse in terms of accuracy. Generally speaking, you can't. Usually the system clock (which is where DateTime.Now
gets its data from) has a resolution of around 10-15 ms. See Eric Lippert's blog post about precision and accuracy for more details.
If you need more accurate timing than this, you may want to look into using an NTP client.
However, it's not clear that you really need millisecond accuracy here. If you don't care about the exact timing - you just want to show the samples in the right order, with "pretty good" accuracy, then the system clock should be fine. I'd advise you to use DateTime.UtcNow
rather than DateTime.Now
though, to avoid time zone issues around daylight saving transitions, etc.
If your question is actually just around converting a DateTime
to a string with millisecond precision, I'd suggest using:
string timestamp = DateTime.UtcNow.ToString("yyyy-MM-dd HH:mm:ss.fff",
CultureInfo.InvariantCulture);
(Note that unlike your sample, this is sortable and less likely to cause confusion around whether it's meant to be "month/day/year" or "day/month/year".)
Solution 2:
This should work:
DateTime.Now.ToString("hh.mm.ss.ffffff");
If you don't need it to be displayed and just need to know the time difference, well don't convert it to a String. Just leave it as, DateTime.Now();
And use TimeSpan
to know the difference between time intervals:
Example
DateTime start;
TimeSpan time;
start = DateTime.Now;
//Do something here
time = DateTime.Now - start;
label1.Text = String.Format("{0}.{1}", time.Seconds, time.Milliseconds.ToString().PadLeft(3, '0'));
Solution 3:
I was looking for a similar solution, base on what was suggested on this thread, I use the following
DateTime.Now.ToString("MM/dd/yyyy hh:mm:ss.fff")
, and it work like charm. Note: that .fff
are the precision numbers that you wish to capture.
Solution 4:
Use DateTime Structure with milliseconds and format like this:
string timestamp = DateTime.UtcNow.ToString("yyyy-MM-dd HH:mm:ss.fff",
CultureInfo.InvariantCulture);
timestamp = timestamp.Replace("-", ".");
Solution 5:
Pyromancer's answer seems pretty good to me, but maybe you wanted:
DateTime.Now.Millisecond
But if you are comparing dates, TimeSpan is the way to go.