Get time in milliseconds using C#

后端 未结 8 1629
你的背包
你的背包 2021-01-30 09:56

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

相关标签:
8条回答
  • 2021-01-30 10:18

    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.

    0 讨论(0)
  • 2021-01-30 10:24

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

    0 讨论(0)
  • 2021-01-30 10:25

    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

    0 讨论(0)
  • 2021-01-30 10:29
    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();
    
    0 讨论(0)
  • 2021-01-30 10:30

    I used DateTime.Now.TimeOfDay.TotalMilliseconds (for current day), hope it helps you out as well.

    0 讨论(0)
  • 2021-01-30 10:32

    Using Stopwatch class we can achieve it from System.Diagnostics.

    Stopwatch stopwatch  = new Stopwatch();
    stopwatch.Start();
    stopwatch.Stop();
    Debug.WriteLine(stopwatch.ElapsedMilliseconds);
    
    0 讨论(0)
提交回复
热议问题