0

I made a function that makes the difference between to dates. I actually want to display the exact posting date with the difference between the current time and the posting date. my result is totally wrong. Below is my function. '517449600' => May 26th 1986. And my result is 7h when I refresh the page it becomes 8h. impossible !

 var difference = (Date.now() - 517449600) * 1000;
        var date = new Date(difference);
        var hours = date.getHours();
        var minutes = date.getMinutes();
        var days = Math.floor(hours / 24);

        var postDate = (days == 0) ? ((hours == 0) ? minutes+' min' : hours+ ' h') : days+ ' day';
        //console.log(postDate);
stephan lemaitre
  • 85
  • 1
  • 1
  • 9

1 Answers1

0

The reason your code is not working is because you are trying to set a date to a timestamp of the difference between 2 timestamps. What you need to do is get the difference between 2 dates (timestamps) and calculate the difference in seconds: http://jsfiddle.net/oo1hh3n2/

var then = 517449600;
var diff = Math.round((new Date().getTime() - (then * 1000)) / 1000);

var s = 1,
    m = s * 60,
    h = m * 60,
    d = h * 24,
    w = d * 7,
    y = w * 52;

var years = Math.floor(diff / y);
var weeks = Math.floor(diff / w);
var days = Math.floor(diff / d);
var hours = Math.floor(diff / h);
var minutes = Math.floor(diff / m);

var time = [];

if (years > 0) {
    time.push(years + 'y');
}

if (weeks > 0) {
    var week = weeks - (years * 52);
    if (week > 0) {
        time.push(week + 'w');
    }
}

if (days > 0) {
    var day = days - (weeks * 7);
    if (day > 0) {
        time.push(day + 'd');
    }
}

if (hours > 0) {
    var hour = hours - (days * 24);
    if (hour > 0) {
        time.push(hour + 'h');
    }
}

if (minutes > 0) {
    var minute = minutes - (hours * 60);
    if (minute > 0) {
        time.push(minute + 'm');
    }
}

if (diff > 0) {
    var second = diff - (minutes * 60);
    if (second > 0) {
        time.push(second + 's');
    }
}

console.log(time.join(' '));

I hope that is the solution you are looking for?

Side Note: JavaScripts Date is not the greatest for logic, eg.

var d = new Date('2014-01-31'); // Fri Jan 31 2014 00:00:00 GMT+0000 (GMT Standard Time)
d.setMonth('+1'); // Mon Mar 03 2014 00:00:00 GMT+0000 (GMT Standard Time)
Gavin Hellyer
  • 328
  • 1
  • 9