Safari日期差异给出了nan

时间:2017-06-20 12:51:13

标签: javascript date safari

我正在使用一个函数从今天的日期和时间中减去特定的日期和时间

<script>
function timeDifference(previous) {

    var msPerMinute = 60 * 1000;
    var msPerHour = msPerMinute * 60;
    var msPerDay = msPerHour * 24;
    var msPerMonth = msPerDay * 30;
    var msPerYear = msPerDay * 365;

    var elapsed = new Date() - new Date(previous);

    if (elapsed < msPerMinute) {
        return Math.round(elapsed/1000) + ' seconds ago';
    }

    else if (elapsed < msPerHour) {
        return Math.round(elapsed/msPerMinute) + ' minutes ago';
    }

    else if (elapsed < msPerDay ) {
        return Math.round(elapsed/msPerHour ) + ' hours ago';
    }

    else if (elapsed < msPerMonth) {
        return Math.round(elapsed/msPerDay) + ' days ago';
    }

    else if (elapsed < msPerYear) {
        return  Math.round(elapsed/msPerMonth) + ' months ago';
    }

    else {
        return Math.round(elapsed/msPerYear ) + ' years ago';
    }
}
</script>

这个功能在firefox,chrome上完美运行但在Safari上给NaN 知道为什么会这样吗?

1 个答案:

答案 0 :(得分:0)

使用时刻代替日期,每件事情都可以正常使用

 <script>
function timeDifference(previous) {

var msPerMinute = 60 * 1000;
var msPerHour = msPerMinute * 60;
var msPerDay = msPerHour * 24;
var msPerMonth = msPerDay * 30;
var msPerYear = msPerDay * 365;

var elapsed = new moment() - new moment(previous);

if (elapsed < msPerMinute) {
    return Math.round(elapsed/1000) + ' seconds ago';
}

else if (elapsed < msPerHour) {
    return Math.round(elapsed/msPerMinute) + ' minutes ago';
}

else if (elapsed < msPerDay ) {
    return Math.round(elapsed/msPerHour ) + ' hours ago';
}

else if (elapsed < msPerMonth) {
    return Math.round(elapsed/msPerDay) + ' days ago';
}

else if (elapsed < msPerYear) {
    return  Math.round(elapsed/msPerMonth) + ' months ago';
}

else {
    return Math.round(elapsed/msPerYear ) + ' years ago';
}
}
 </script>