Get DateTime.Now with milliseconds precision

466,147

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.

Share:
466,147

Related videos on Youtube

LuckyHK
Author by

LuckyHK

Updated on April 09, 2021

Comments

  • LuckyHK
    LuckyHK about 3 years

    How can I exactly construct a time stamp of actual time with milliseconds precision?

    I need something like 16.4.2013 9:48:00:123. Is this possible? I have an application, where I sample values 10 times per second, and I need to show them in a graph.

  • Contango
    Contango almost 10 years
    Note: If you're comparing the difference between two DateTimes as a TimeSpan, you need TotalMilliseconds. Milliseconds holds the current Milliseconds counter, which is never greater than 1000, whereas TotalMilliseconds holds the total milliseconds elapsed since the epoch.
  • Peter Mortensen
    Peter Mortensen over 7 years
    Yes, but the actual resolution of DateTime.Now may not be more than about 16 ms.
  • Jaider
    Jaider almost 7 years
    If the date is in afternoon (4PM) will shows as in the morning. FIX: Use HH (military time) or add tt (PM or AM). As shown in this example: repl.it/KGr3/1
  • Jon Skeet
    Jon Skeet over 6 years
    @antonio: With no more information than "don't works" I can't provide any more help.
  • antonio
    antonio over 6 years
    Yes, I can provide more info: "{0:yyyyMMdd HH:mm:ss.fff}", DateTime.UtcNow -> 20180502 11:07:20.000 Win32.GetSystemTime(ref stime) -> 2018,2,5,11,7,20,0 (y m d h mm ss ms) I can create a instance of date time with milliseconds: var dt = new DateTime(2018, 5, 2, 19, 34, 55, 200); "{0:yyyyMMdd HH:mm:ss.fff}", dt -> 20180502 19:34:55.200 .Net compact framework, Windows Embedded Compact 7, on ARM Cortex-A8
  • Jon Skeet
    Jon Skeet over 6 years
    @antonio: So it sounds like the version of .NET you're using on the hardware you're using simply doesn't provide subsecond accuracy - or you happened to call it on a second boundary. (If you keep hitting DateTime.UtcNow repeatedly, does it only ever increment once per second? You haven't shown that.)
  • antonio
    antonio over 6 years
    When I retrieve Ticks from DateTime.Now, the value come truncated: Ticks 636534596580000000 DateTime from Ticks 20180205 20:34:18.000. the limitation is in the hard/software, i think. I have using Stopwatch class, instead Thanks Jon
  • Jon Skeet
    Jon Skeet over 6 years
    @antonio: It's probably worth creating a new question with full details of the device involved at this point.
  • Muhammet Göktürk Ayan
    Muhammet Göktürk Ayan almost 6 years
    Thank you so much. I've been searching this so long. Is it cause any performance issues and is it safe to use production code?
  • kuldeep
    kuldeep almost 4 years
    @JonSkeet I am struggling to understand 2020-09-04T14:29:40.101935+02:00 the miliseconds part here, why is it like 101395 ? I mean i expecte 1 second to have like 1000 ms , and this number looks bigger than that ? What does the last 101395 actually represents in a UTC format ?
  • Jon Skeet
    Jon Skeet almost 4 years
    @kuldeep: That's not milliseconds, that's microseconds. But I've no idea where that came from - I suspect you should ask a new question.
  • kuldeep
    kuldeep almost 4 years
    @JonSkeet .. somehow i am unable to ask a new question on SO. This was saved in postgres DB as timestamptz from datetime.UtcNow field from .net core app !
  • Jon Skeet
    Jon Skeet almost 4 years
    @kuldeep: I'm afraid if you've asked sufficiently bad questions to be question-banned, I'm not going to try to bypass that by getting into what should be another question via comments. I suggest you edit your old questions to be better, to try to remove the ban.
  • Nae
    Nae almost 3 years
    Note that the most precision for sub-seconds is apparently 7, as in "hh.mm.ss.fffffff".

Related