Get DateTime.Now with milliseconds precision

前端 未结 11 1471
没有蜡笔的小新
没有蜡笔的小新 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:51

    The trouble with DateTime.UtcNow and DateTime.Now is that, depending on the computer and operating system, it may only be accurate to between 10 and 15 milliseconds. However, on windows computers one can use by using the low level function GetSystemTimePreciseAsFileTime to get microsecond accuracy, see the function GetTimeStamp() below.

        [System.Security.SuppressUnmanagedCodeSecurity, System.Runtime.InteropServices.DllImport("kernel32.dll")]
        static extern void GetSystemTimePreciseAsFileTime(out FileTime pFileTime);
    
        [System.Runtime.InteropServices.StructLayout(System.Runtime.InteropServices.LayoutKind.Sequential)]
        public struct FileTime  {
            public const long FILETIME_TO_DATETIMETICKS = 504911232000000000;   // 146097 = days in 400 year Gregorian calendar cycle. 504911232000000000 = 4 * 146097 * 86400 * 1E7
            public uint TimeLow;    // least significant digits
            public uint TimeHigh;   // most sifnificant digits
            public long TimeStamp_FileTimeTicks { get { return TimeHigh * 4294967296 + TimeLow; } }     // ticks since 1-Jan-1601 (1 tick = 100 nanosecs). 4294967296 = 2^32
            public DateTime dateTime { get { return new DateTime(TimeStamp_FileTimeTicks + FILETIME_TO_DATETIMETICKS); } }
        }
    
        public static DateTime GetTimeStamp() { 
            FileTime ft; GetSystemTimePreciseAsFileTime(out ft);
            return ft.dateTime;
        }
    

提交回复
热议问题