首页 文章

以秒为单位获取两个日期之间的时差

提问于
浏览
100

我试图在几秒钟内得到两个日期之间的差异 . 逻辑是这样的:

  • 设定一个现在的初始日期;

  • 设置一个最终日期,该日期将是初始日期加上未来的一些秒数(例如,假设为15)

  • 得到这两者之间的差异(秒数)

我之所以这么做是因为最后的日期/时间取决于其他一些变量而且它永远不会相同(这取决于用户做某事的速度),而且我还存储了其他事情的初始日期 .

我一直在尝试这样的事情:

var _initial = new Date(),
    _initial = _initial.setDate(_initial.getDate()),
    _final = new Date(_initial);
    _final = _final.setDate(_final.getDate() + 15 / 1000 * 60);

var dif = Math.round((_final - _initial) / (1000 * 60));

问题是我从来没有得到正确的区别 . 我试着用_2932650分开,这会留给我秒,但我从来没有做对 . 那么我的逻辑有什么不对?我可能会犯一些愚蠢的错误,因为它已经很晚了,但令我烦恼的是我无法让它工作:)

6 回答

  • 202

    守则

    var startDate = new Date();
    // Do your operations
    var endDate   = new Date();
    var seconds = (endDate.getTime() - startDate.getTime()) / 1000;
    

    或者甚至更简单 (endDate - startDate) / 1000 ,如评论中指出的那样,除非你使用的是打字稿 .


    解释

    你需要为 Date 对象调用 getTime() 方法,然后简单地减去它们并除以1000(因为它's originally in milliseconds). As an extra, when you'调用 getDate() 方法,你're in fact getting the day of the month as an integer between 1 and 31 (not zero based) as opposed to the epoch time you'得到调用 getTime() 方法,表示自1970年1月1日以来的毫秒数,00:00


    兰特

    根据您的日期相关操作,您可能希望投资集成一个库,如date.jsmoment.js,这使开发人员更容易,但这只是个人偏好的问题 .

    例如在moment.js中我们会做 moment1.diff(moment2, "seconds") 这很漂亮 .


    这个答案的有用文档

  • 3
    <script type="text/javascript">
    var _initial = '2015-05-21T10:17:28.593Z';
    var fromTime = new Date(_initial);
    var toTime = new Date();
    
    var differenceTravel = toTime.getTime() - fromTime.getTime();
    var seconds = Math.floor((differenceTravel) / (1000));
    document.write('+ seconds +');
    </script>
    
  • 0

    您可以使用 new Date().getTime() 获取时间戳 . 然后你可以计算结束和开始之间的差异,最后将时间戳 ms 变换为 s .

    const start = new Date().getTime();
    const end = new Date().getTime();
    
    const diff = end - start;
    const seconds = Math.floor(diff / 1000 % 60);
    
  • 1

    尝试使用高级编程语言的专用函数 . JavaScript .getSeconds(); 适合这里:

    var specifiedTime = new Date("November 02, 2017 06:00:00");
    var specifiedTimeSeconds = specifiedTime.getSeconds(); 
    
    var currentTime = new Date();
    var currentTimeSeconds = currentTime.getSeconds(); 
    
    alert(specifiedTimeSeconds-currentTimeSeconds);
    
  • 0

    使用momentjs在现在和10分钟之间的时间差

    let start_time = moment().format('YYYY-MM-DD HH:mm:ss');
    let next_time = moment().add(10, 'm').format('YYYY-MM-DD HH:mm:ss');
    
    let diff_milliseconds = Date.parse(next_time) - Date.parse(star_time);
    let diff_seconds = diff_milliseconds * 1000;
    
  • 0

    下面的代码将给出秒的时差 .

    var date1 = new Date(); // current date
        var date2 = new Date("06/26/2018"); // mm/dd/yyyy format
        var timeDiff = Math.abs(date2.getTime() - date1.getTime()); // in miliseconds
        var timeDiffInSecond = Math.ceil(timeDiff / 1000); // in second
    
        alert(timeDiffInSecond );
    

相关问题