0
votes

How to obtain difference in minutes between two raw dates in javascript? i.e. to use as '2 minutes ago', '10 minutes ago', etc.

By RAW I mean this format -> 2015-02-05T03:11:33.301Z (var x = new Date())

This is what I have but I always get NaN in the return value...

function getMinutesBetweenDates(startDate, index) {
    var endDate = new Date();
    var diff = endDate - startDate;
    return (diff / 60000);
}

Thanks for your help.

3
how are you calling this function??Mritunjay
getMinutesBetweenDates(aux[i]['date'], i); imagine aux[i]['date'] is another new Date() obtained minutes beforeAzael Alanis
Provided startDate is a Date, then the function will return a value in decimal minutes. So truncate the return value to remove the decimal part and add ' minutes ago'.RobG
If you are getting NaN, then startDate isn't a Date object. Is (startDate instanceof Date)?neouser99
damn... I didn't thought of that... the startDate was parsed with JSON.parse before calling the function... so it's only the format of the date not the instanceof Date :(Azael Alanis

3 Answers

0
votes

I think problem would be the way you will be calling your function.

You should call it like bellow

var startDate = new Date("2015-02-05T03:11:33.301Z");
getMinutesBetweenDates(startDate); 

It will print something like bellow

11.711916666666667

Just use Math.floor before returning value to get the result as 11.

0
votes

Modern browsers will correctly parse a string in the OP format (a version of ISO 8601) however older browsers like IE 8 and lower will not. It's much safer to manually parse the string:

function parseISOutc(s) {
  var b = s.split(/\D/);
  return new Date(Date.UTC(b[0], b[1] - 1, b[2], b[3], b[4], b[5], (b[6] || 0)));
}

Now your function can be:

function getMinutesBetweenDates(startDate) {
    return ((new Date() - parseISOutc(startDate)) / 6e4 | 0) + ' minutes ago';
}

The index parameter was unused so I removed it.

0
votes

Try this,

You have to convert startDate to a Date object even it's in the JSON format of Date object. The reason is, when you subtract, the valueOf method of the Date objects are called and subtracted. The return values of valueOf method are different in Date objects and JSON strings.

function getMinutesBetweenDates(startDate) {
    var endDate = new Date();
    var startDate = new Date(startDate);
    document.write(startDate.valueOf());
    var diff = endDate - startDate;
    return (diff / 60000);
}

document.write(getMinutesBetweenDates("2015-02-05T03:11:33.301Z"));