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
If you still want a date instead of a string like the other answers, just add this extension method.
public static DateTime ToMillisecondPrecision(this DateTime d) {
return new DateTime(d.Year, d.Month, d.Day, d.Hour, d.Minute,
d.Second, d.Millisecond, d.Kind);
}
try using datetime.now.ticks. this provides nanosecond precision. taking the delta of two ticks (stoptick - starttick)/10,000 is the millisecond of specified interval.
https://docs.microsoft.com/en-us/dotnet/api/system.datetime.ticks?view=netframework-4.7.2
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.
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.
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;
}
public long millis() {
return (long.MaxValue + DateTime.Now.ToBinary()) / 10000;
}
If you want microseconds, just change 10000
to 10
, and if you want the 10th of micro, delete / 10000
.