Java System.currentTimeMillis() equivalent in C#

前端 未结 11 1085
-上瘾入骨i
-上瘾入骨i 2020-12-13 01:18

What is the equivalent of Java\'s System.currentTimeMillis() in C#?

相关标签:
11条回答
  • 2020-12-13 01:53

    We could also get a little fancy and do it as an extension method, so that it hangs off the DateTime class:

    public static class DateTimeExtensions
    {
        private static DateTime Jan1st1970 = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
        public static long currentTimeMillis(this DateTime d)
        {
            return (long) ((DateTime.UtcNow - Jan1st1970).TotalMilliseconds);
        }
    }
    
    0 讨论(0)
  • 2020-12-13 01:56

    If you want a timestamp to be compared between different processes, different languages (Java, C, C#), under GNU/Linux and Windows (Seven at least):

    C#:

    private static long nanoTime() {
       long nano = 10000L * Stopwatch.GetTimestamp();
       nano /= TimeSpan.TicksPerMillisecond;
       nano *= 100L;
       return nano;
    }
    

    Java:

    java.lang.System.nanoTime();
    

    C GNU/Linux:

    static int64_t hpms_nano() {
       struct timespec t;
       clock_gettime( CLOCK_MONOTONIC, &t );
       int64_t nano = t.tv_sec;
       nano *= 1000;
       nano *= 1000;
       nano *= 1000;
       nano += t.tv_nsec;
       return nano;
    }
    

    C Windows:

    static int64_t hpms_nano() {
       static LARGE_INTEGER ticksPerSecond;
       if( ticksPerSecond.QuadPart == 0 ) {
          QueryPerformanceFrequency( &ticksPerSecond );
       }
       LARGE_INTEGER ticks;
       QueryPerformanceCounter( &ticks );
       uint64_t nano = ( 1000*1000*10UL * ticks.QuadPart ) / ticksPerSecond.QuadPart;
       nano *= 100UL;
       return nano;
    }
    
    0 讨论(0)
  • 2020-12-13 01:59

    An alternative:

    private static readonly DateTime Jan1st1970 = new DateTime
        (1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
    
    public static long CurrentTimeMillis()
    {
        return (long) (DateTime.UtcNow - Jan1st1970).TotalMilliseconds;
    }
    
    0 讨论(0)
  • 2020-12-13 02:01
    DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
    
    0 讨论(0)
  • 2020-12-13 02:03

    If you are interested in TIMING, add a reference to System.Diagnostics and use a Stopwatch.

    For example:

    var sw = Stopwatch.StartNew();
    ...
    var elapsedStage1 = sw.ElapsedMilliseconds;
    ...
    var elapsedStage2 = sw.ElapsedMilliseconds;
    ...
    sw.Stop();
    
    0 讨论(0)
  • 2020-12-13 02:04

    The framework doesn't include the old seconds (or milliseconds) since 1970. The closest you get is DateTime.Ticks which is the number of 100-nanoseconds since january 1st 0001.

    0 讨论(0)
提交回复
热议问题