如何修改此功能以考虑“月”和“年”?

时间:2012-03-20 09:46:24

标签: javascript math datetime date time

function prettyDate(time){
    var date = time,
        diff = (((new Date()).getTime() - date.getTime()) / 1000),
        day_diff = Math.floor(diff / 86400);
    if ( isNaN(day_diff) || day_diff < 0 || day_diff >= 31 ){
        return;
    }
    return day_diff == 0 && (
            diff < 60 && Math.floor(diff) + " seconds" ||
            diff < 120 && "1 minute" ||
            diff < 3600 && Math.floor( diff / 60 ) + " min" ||
            diff < 7200 && "1 hour" ||
            diff < 86400 && Math.floor( diff / 3600 ) + " hours") ||
        day_diff == 1 && "1 day" ||
        day_diff < 7 && day_diff + " days" ||
        day_diff < 31 && Math.ceil( day_diff / 7 ) + " weeks";
}

我的朋友帮我写了这个函数,把日期变成了“漂亮的日期”。问题是,现在它没有处理几个月。如果您查看代码,当天数差异超过31天时,它将不返回任何内容。

我可以做几个月和几年的工作?

这会照顾它,添加到最后一行吗?

Math.ceil( day_diff / 31 ) + " months";

1 个答案:

答案 0 :(得分:1)

您需要在return表达式的末尾添加一些子句,并删除day_diff >= 31后卫:

function prettyDate(time){
    var date = time,
        diff = (((new Date()).getTime() - date.getTime()) / 1000),
        day_diff = Math.floor(diff / 86400);
    if ( isNaN(day_diff) || day_diff < 0){
        return;
    }
    return day_diff == 0 && (
            diff < 60 && Math.floor(diff) + " seconds" ||
            diff < 120 && "1 minute" ||
            diff < 3600 && Math.floor( diff / 60 ) + " min" ||
            diff < 7200 && "1 hour" ||
            diff < 86400 && Math.floor( diff / 3600 ) + " hours") ||
        day_diff == 1 && "1 day" ||
        day_diff < 7 && day_diff + " days" ||
        day_diff < 31 && Math.ceil( day_diff / 7 ) + " weeks" ||
        day_diff < 365 && Math.ceil( day_diff / 31 ) + " months" ||
        Math.ceil( day_diff / 365 ) + " years";
}

<强> See it in action