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构造函数可以理解的格式.
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)
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)
如果您希望在挂钟时间,当地时区和日光节约意识方面有所不同.
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)
差分或秒以相同的方式.