I\'m making a program in which I need to get the time in milliseconds. By time, I mean a number that is never equal to itself, and is always 1000 numbers bigger than it was a se
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.
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).
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
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();
I used DateTime.Now.TimeOfDay.TotalMilliseconds (for current day), hope it helps you out as well.
Using Stopwatch class we can achieve it from System.Diagnostics
.
Stopwatch stopwatch = new Stopwatch();
stopwatch.Start();
stopwatch.Stop();
Debug.WriteLine(stopwatch.ElapsedMilliseconds);