2个日期之间的差异导致错误

时间:2014-10-30 05:22:58

标签: javascript date

我创造了一个能够区分日期的功能。我实际上想要显示确切的发布日期,以及当前时间和发布日期之间的差异。我的结果完全错了。以下是我的功能。 '517449600'=> 1986年5月26日。我的结果是7h,当我刷新页面它变成8h。不可能!

 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);

1 个答案:

答案 0 :(得分:0)

您的代码无法正常工作的原因是您尝试将日期设置为2个时间戳之间差异的时间戳。您需要做的是获取2个日期(时间戳)之间的差异并计算以秒为单位的差异: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(' '));

我希望这是您正在寻找的解决方案吗?

附注:JavaScripts日期不是逻辑上最好的,例如。

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)