C# version of Javascript Date.getTime()

前端 未结 8 1296
予麋鹿
予麋鹿 2021-02-01 21:11

What is the best way in c# to get the same result of javascript date.gettime() call?

The getTime() method returns the number of milliseconds since midnigh

相关标签:
8条回答
  • 2021-02-01 21:42

    You can use this solution:

    private int GetTime()
    {
       var time = (DateTime.Now.ToUniversalTime() - new DateTime(1970, 1, 1));
       return (int)(time.TotalMilliseconds + 0.5);
    }
    
     
    
    0 讨论(0)
  • 2021-02-01 21:48

    The currently accepted answer returns an int which is incorrect. It has to be Int64 or long. This is just rewriting the correct answer provided by Matt Johnson-Pint (and edited by Adaptabi) as one line. Please accept Matt Johnson-Pint's answer. I checked it against actual javascript new Date().getTime() in the console to verify it returns the same number.

    long JavascriptGetTime()
    {
        return (long)DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc)).TotalMilliseconds;            
    }
    
    0 讨论(0)
提交回复
热议问题