我有一个包含日期/时间的网格字段,我需要知道它和当前日期/时间之间的区别。这样做的最佳方式是什么?
日期以“2011-02-07 15:13:06”的方式存储。
我有一个包含日期/时间的网格字段,我需要知道它和当前日期/时间之间的区别。这样做的最佳方式是什么?
日期以“2011-02-07 15:13:06”的方式存储。
当前回答
除非你在同一个浏览器客户端上减去日期,并且不关心像日光节约时间变化这样的边缘情况,你可能最好使用moment.js,它提供了强大的本地化api。例如,这是我在utils.js中所拥有的:
subtractDates: function(date1, date2) {
return moment.subtract(date1, date2).milliseconds();
},
millisecondsSince: function(dateSince) {
return moment().subtract(dateSince).milliseconds();
},
其他回答
这将给出两个日期之间的差异,以毫秒为单位
var diff = Math.abs(date1 - date2);
在你的例子中,应该是
var diff = Math.abs(new Date() - compareDate);
您需要确保compareDate是一个有效的Date对象。
像这样的东西可能对你有用
var diff = Math.abs(new Date() - new Date(dateStr.replace(/-/g,'/')));
例如,将"2011-02-07 15:13:06"转换为新的Date('2011/02/07 15:13:06'),这是Date构造函数可以理解的格式。
您可以使用getTime()方法将日期转换为自1970年1月1日以来的毫秒数。然后,您可以轻松地对日期进行任何算术运算。当然,您可以使用setTime()将数字转换回日期。请看下面的例子。
只需减去两个日期对象。
var d1 = new Date(); //"now"
var d2 = new Date("2011/02/01"); // some date
var diff = Math.abs(d1-d2); // difference in milliseconds
如果您希望获得不同的挂钟时间,为当地时区和日光节约意识。
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;
};
Test
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);
});
Diff分或秒是同样的方式。
除非你在同一个浏览器客户端上减去日期,并且不关心像日光节约时间变化这样的边缘情况,你可能最好使用moment.js,它提供了强大的本地化api。例如,这是我在utils.js中所拥有的:
subtractDates: function(date1, date2) {
return moment.subtract(date1, date2).milliseconds();
},
millisecondsSince: function(dateSince) {
return moment().subtract(dateSince).milliseconds();
},