JavaScript NTP time

后端 未结 3 1846
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-04 01:50

I\'m writing a counting script who counts the time between an old date and today.
Everything worked good until I tested on a computer with wrong date and saw the resul

3条回答
  •  醉话见心
    2020-12-04 02:24

    put this right at the top of your document:

    var clientTime = new Date();
    

    and this right at the bottom of your document:

    var serverTime = new Date("");
    var deltaTime = serverTime - clientTime; // in milliseconds (expected accuracy: < 1 second)
    

    then, if you need to know the duration of something:

    var startTime = new Date();
    
    // [processing...]
    
    var endTime = new Date();
    var duration = endTime - startTime; // in milliseconds
    var startTimeServer = startTime + deltaTime;
    var endTimeServer = endTime + deltaTime;
    

提交回复
热议问题