如何在javascript中减去日期/时间?

Ahm*_*rid 156 javascript date

我在包含日期/时间的网格中有一个字段,我需要知道它与当前日期/时间之间的差异.这可能是最好的方法吗?

Dav*_*und 204

这将为您提供两个日期之间的差异,以毫秒为单位

var diff = Math.abs(date1 - date2);
Run Code Online (Sandbox Code Playgroud)

在你的例子中,它是

var diff = Math.abs(new Date() - compareDate);
Run Code Online (Sandbox Code Playgroud)

您需要确保它compareDate是一个有效的Date对象.

这样的事可能对你有用

var diff = Math.abs(new Date() - new Date(dateStr.replace(/-/g,'/')));
Run Code Online (Sandbox Code Playgroud)

"2011-02-07 15:13:06"转入new Date('2011/02/07 15:13:06'),这是Date构造函数可以理解的格式.

  • 在TypeScript中,当我尝试这样做时,我得到一个tslint错误:var diff = Math.abs(new Date() - compareDate); (2认同)
  • 如果您采用夏令时,这将给出错误的结果 (2认同)

paw*_*wel 28

您可以减去两个日期对象.

var d1 = new Date(); //"now"
var d2 = new Date("2011/02/01")  // some date
var diff = Math.abs(d1-d2);  // difference in milliseconds
Run Code Online (Sandbox Code Playgroud)

  • `(新日期(“1970/01/02”)-新日期(“1969/12/29”))/1000/60/60/24 === 4` (4认同)
  • @Ethan 是的,它会被添加,这就是重点。3和-3的区别是6,`3 - (-3) == 3 + 3 == 6` (3认同)

Shi*_*hah 16

除非您在同一浏览器客户端上减去日期并且不关心日光节省时间更改等边缘情况,否则最好使用提供功能强大的本地化API的moment.js.例如,这就是我在utils.js中的内容:

subtractDates: function(date1, date2) {
    return moment.subtract(date1, date2).milliseconds();
},
millisecondsSince: function(dateSince) {
    return moment().subtract(dateSince).milliseconds();
},
Run Code Online (Sandbox Code Playgroud)

  • 6 年后,moment.js 被认为对于日期的使用来说过于臃肿和过重。考虑这篇文章并使用一些替代方案 - https://dev.to/aminnairi/you-probously-don-t-need-moment-js-493m (4认同)

Ole*_*leg 12

您可以使用getTime()方法将转换Date为自1970年1月1日以来的毫秒数.然后您可以轻松地对日期进行任何算术运算.当然,你可以数转换回DatesetTime().看这里的例子.


Pav*_*ara 7

如果您希望在挂钟时间,当地时区和日光节约意识方面有所不同.


Date.prototype.diffDays = function (date: Date): number {

    var utcThis = Date.UTC(this.getFullYear(), this.getMonth(), this.getDate(), this.getHours(), this.getMinutes(), this.getSeconds(), this.getMilliseconds());
    var utcOther = Date.UTC(date.getFullYear(), date.getMonth(), date.getDate(), date.getHours(), date.getMinutes(), date.getSeconds(), date.getMilliseconds());

    return (utcThis - utcOther) / 86400000;
};

Run Code Online (Sandbox Code Playgroud)

测试


it('diffDays - Czech DST', function () {
    // expect this to parse as local time
    // with Czech calendar DST change happened 2012-03-25 02:00
    var pre = new Date('2012/03/24 03:04:05');
    var post = new Date('2012/03/27 03:04:05');

    // regardless DST, you still wish to see 3 days
    expect(pre.diffDays(post)).toEqual(-3);
});
Run Code Online (Sandbox Code Playgroud)

差分或秒以相同的方式.