C# version of Javascript Date.getTime()

前端 未结 8 1312
予麋鹿
予麋鹿 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:38

    Here is an extension method based off Enigma State's answer

    public static Int64 GetJavascriptTimeStamp(this DateTime dt)
    {
        var nineteenseventy = new DateTime(1970, 1, 1);
        var timeElapsed = (dt.ToUniversalTime() - nineteenseventy);
        return (Int64)(timeElapsed.TotalMilliseconds + 0.5);
    }
    

    To use it for the current time:

    var timeStamp = DateTime.Now.GetJavascriptTimeStamp();

提交回复
热议问题