You can use DiffSeconds() built-in function and multiply the result by 1000. The output will be milliseconds.
long milliseconds = DateTime.Now.Ticks / TimeSpan.TicksPerMillisecond;
This is actually how the various Unix conversion methods are implemented in the DateTimeOffset
class (.NET Framework 4.6+, .NET Standard 1.3+):
long milliseconds = DateTimeOffset.Now.ToUnixTimeMilliseconds();
Use the Stopwatch
class.
Provides a set of methods and properties that you can use to accurately measure elapsed time.
There is some good info on implementing it here:
Performance Tests: Precise Run Time Measurements with System.Diagnostics.Stopwatch
The DateTime.Ticks
property gets the number of ticks that represent the date and time.
10,000 Ticks is a millisecond (10,000,000 ticks per second).
I use the following class. I found it on the Internet once, postulated to be the best NOW().
/// <summary>Class to get current timestamp with enough precision</summary>
static class CurrentMillis
{
private static readonly DateTime Jan1St1970 = new DateTime (1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
/// <summary>Get extra long current timestamp</summary>
public static long Millis { get { return (long)((DateTime.UtcNow - Jan1St1970).TotalMilliseconds); } }
}
Source unknown.
You can try the QueryPerformanceCounter
native method. See http://www.pinvoke.net/default.aspx/kernel32/QueryPerformanceCounter.html for more information. This is what the Stopwatch
class uses.
See How to get timestamp of tick precision in .NET / C#? for more information.
Stopwatch.GetTimestamp()
gives access to this method:
public static long GetTimestamp() {
if(IsHighResolution) {
long timestamp = 0;
SafeNativeMethods.QueryPerformanceCounter(out timestamp);
return timestamp;
}
else {
return DateTime.UtcNow.Ticks;
}
}
I used DateTime.Now.TimeOfDay.TotalMilliseconds (for current day), hope it helps you out as well.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With