225

I have a field at a grid containing date/time and I need to know the difference between that and the current date/time. What could be the best way of doing so?

The dates are stored like "2011-02-07 15:13:06".

Sebastian Simon
  • 18,263
  • 7
  • 55
  • 75
Ahmad Farid
  • 14,398
  • 45
  • 96
  • 136

5 Answers5

277

This will give you the difference between two dates, in milliseconds

var diff = Math.abs(date1 - date2);

In your example, it'd be

var diff = Math.abs(new Date() - compareDate);

You need to make sure that compareDate is a valid Date object.

Something like this will probably work for you

var diff = Math.abs(new Date() - new Date(dateStr.replace(/-/g,'/')));

i.e. turning "2011-02-07 15:13:06" into new Date('2011/02/07 15:13:06'), which is a format the Date constructor can comprehend.

David Hedlund
  • 128,221
  • 31
  • 203
  • 222
  • 1
    this ignores DTS handling for local timezone (works well with UTC) – Pavel Savara Feb 08 '13 at 18:11
  • 4
    in TypeScript I get a tslint error when I try to do this: var diff = Math.abs(new Date() - compareDate); – Devid Sep 16 '17 at 10:32
  • 1
    @Ethan: It does work. The time _should_ be added. The difference between 1980/1/1 and 1960/1/1 is the ten years between epoch and 1980, _plus_ the 10 years between 1960 and epoch. The difference between 1980/1/1 and 1975/1/1 on the other hand is the ten years between epoch and 1980, _minus_ the 5 years between 1975 and epoch. Both scenarios covered. – David Hedlund Jan 07 '19 at 14:22
  • @DavidHedlund Yup, you're totally right. Brain fart on my end; deleted the comment. – Ethan Jan 15 '19 at 23:53
  • 2
    this will give a wrong result if you are on daylight savings – shamaseen Oct 29 '20 at 22:50
  • `var d = new Date(); var start = new Date(d.setDate(d.getDate() - 7)) ; $("#txtFromDate").attr("value", start.toISOString().substring(0, 10).replaceAll("-", "/"));` – komeil shahmoradi Nov 24 '21 at 06:09
55

You can just substract two date objects.

var d1 = new Date(); //"now"
var d2 = new Date("2011/02/01");  // some date
var diff = Math.abs(d1-d2);  // difference in milliseconds
MrHaze
  • 3,786
  • 3
  • 26
  • 47
pawel
  • 35,827
  • 7
  • 56
  • 53
  • This won't work if d2 is before 1970; in that case, its timestamp in milliseconds will be negative, and the time between the unix epoch and d2 will actually get added to d1. – Ethan Jan 07 '19 at 07:45
  • 4
    @Ethan Yes it will get added, that's the point. The difference between 3 and -3 is 6, `3 - (-3) == 3 + 3 == 6` – pawel Jan 07 '19 at 13:01
  • 5
    `(new Date("1970/01/02") - new Date("1969/12/29")) /1000/60/60/24 === 4` – pawel Jan 07 '19 at 13:04
18

If you wish to get difference in wall clock time, for local timezone and with day-light saving awareness.


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 minutes or seconds is in same fashion.

Pavel Savara
  • 3,427
  • 1
  • 30
  • 35
  • Brilliant answer, I was searching the whole web for a solution to the daylight saving issue and at last, you came by! – shamaseen Oct 29 '20 at 23:07
18

Unless you are subtracting dates on same browser client and don't care about edge cases like day light saving time changes, you are probably better off using moment.js which offers powerful localized APIs. For example, this is what I have in my utils.js:

subtractDates: function(date1, date2) {
    return moment.subtract(date1, date2).milliseconds();
},
millisecondsSince: function(dateSince) {
    return moment().subtract(dateSince).milliseconds();
},
Shital Shah
  • 63,284
  • 17
  • 238
  • 185
  • 3
    6 years later, moment.js is considered far too bloated and overweight for its uses with dates. Consider this article and use some alternatives - https://dev.to/aminnairi/you-probably-don-t-need-moment-js-493m – David Maness Jan 31 '21 at 02:03
18

You can use getTime() method to convert the Date to the number of milliseconds since January 1, 1970. Then you can easy do any arithmetic operations with the dates. Of course you can convert the number back to the Date with setTime(). See here an example.

Simson
  • 3,373
  • 2
  • 24
  • 38
Oleg
  • 220,925
  • 34
  • 403
  • 798