Get DateTime.Now with milliseconds precision

前端 未结 11 1426
没有蜡笔的小新
没有蜡笔的小新 2020-11-29 16:06

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 applic

相关标签:
11条回答
  • 2020-11-29 16:55

    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'));
    
    0 讨论(0)
  • 2020-11-29 16:55

    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("-", ".");
    
    0 讨论(0)
  • 2020-11-29 17:00

    As far as I understand the question, you can go for:

    DateTime dateTime = DateTime.Now;
    DateTime dateTimeInMilliseconds = dateTime.AddTicks(-1 * dateTime.Ticks % 10000); 
    

    This will cut off ticks smaller than 1 millisecond.

    0 讨论(0)
  • 2020-11-29 17:04

    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".)

    0 讨论(0)
  • 2020-11-29 17:09

    DateTime.Now.ToString("ddMMyyyyhhmmssffff")

    0 讨论(0)
提交回复
热议问题