Problem
How can I precisely produce a millisecond-accurate time stamp of actual time?
I’m looking for something similar to 16.4.2013 9:48:00:123. Is that even possible? I’m working on an application that samples values 10 times per second and displays them in a graph.
Asked by LuckyHK
Solution #1
I believe you’re referring to millisecond precision. DateTime offers a lot of precision, but it’s not really accurate. In most cases, you won’t be able to. The system clock (from which DateTime.Now gets its data) usually has a precision of 10-15 milliseconds. For further information, see Eric Lippert’s blog post on precision and accuracy.
If you require more precise timing, you may want to consider utilizing an NTP client.
However, it’s not apparent that millisecond precision is required here. If you don’t care about perfect timing and only want the samples to appear in the correct order with “very excellent” precision, the system clock should suffice. Instead of DateTime, I recommend using DateTime.UtcNow. However, in order to avoid time zone difficulties during daylight saving time transitions and other events,
If all you want to do is convert a DateTime to a string with millisecond precision, I’d recommend using:
string timestamp = DateTime.UtcNow.ToString("yyyy-MM-dd HH:mm:ss.fff",
CultureInfo.InvariantCulture);
(Note that this is sortable, unlike your sample, and is less likely to cause confusion about whether it should be “month/day/year” or “day/month/year.”)
Answered by Jon Skeet
Solution #2
This should work:
DateTime.Now.ToString("hh.mm.ss.ffffff");
If you only need to know the time difference and don’t require it to be shown, don’t convert it to a String. Simply call it DateTime. Now();
Also, to get the difference between time intervals, use TimeSpan:
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'));
Answered by Pyromancer
Solution #3
I was seeking for a similar approach, so I used the DateTime that was provided in this discussion. Now. ToString(“MM/dd/yyyy hh:mm:ss.fff”) works perfectly. Note that the precision numbers you want to capture are in the format.fffffffffffffffffffffffffffff
Answered by Jozcar
Solution #4
Use a millisecond DateTime Structure and format it like this:
string timestamp = DateTime.UtcNow.ToString("yyyy-MM-dd HH:mm:ss.fff",
CultureInfo.InvariantCulture);
timestamp = timestamp.Replace("-", ".");
Answered by Jacman
Solution #5
Pyromancer’s response sounds adequate to me, but perhaps you desired:
DateTime.Now.Millisecond
When comparing dates, though, TimeSpan is the way to go.
Answered by Renae
Post is based on https://stackoverflow.com/questions/16032451/get-datetime-now-with-milliseconds-precision