的JavaScript。几个月和几年的漂亮约会

时间:2011-06-01 20:02:57

标签: javascript

我有以下脚本将日期转换为漂亮的日期。它完美地运作 很好,但只有几个星期。我需要它可以工作好几个月甚至几年。

如何修改此代码才能生效?

function prettyDate(time) {

    var date = new Date((time || "").replace(/-/g,"/").replace(/[TZ]/g," ")),
        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 && "just now" ||
            diff < 120 && "1 minute ago" ||
            diff < 3600 && Math.floor( diff / 60 ) + " minutes ago" ||
            diff < 7200 && "1 hour ago" ||
            diff < 86400 && Math.floor( diff / 3600 ) + " hours ago") ||
        day_diff == 1 && "Yesterday" ||
        day_diff < 7 && day_diff + " days ago" ||
        day_diff < 31 && Math.ceil( day_diff / 7 ) + " weeks ago";
}

3 个答案:

答案 0 :(得分:8)

我会看一下:http://ejohn.org/blog/javascript-pretty-date/。查看评论以获取更多信息。

见这里:http://jsfiddle.net/MarkSchultheiss/cgMZz/1/

在BIT更多阅读后,我看到此处发布的更新:http://www.zachleat.com/web/yet-another-pretty-date-javascript/并最终转移到:https://github.com/zachleat/Humane-Dates,所有这些都归功于程序员!

答案 1 :(得分:0)

我使用a dateDiff extension for dates和此(toAge)扩展程序的组合:

Date.prototype.toAge = function() {
// all comparisons are based on GMT time

var s = "";
var span = 0;
var uom = "";

// get the current time in GMT
var oDiff = this.dateDiff(new Date(new Date().toUTCString().replace(" UTC", "").replace(" GMT", "")));

if (oDiff.TotalMinutes < 59) {
    span = Math.round(oDiff.TotalMinutes);
    uom = "min";
}
else {
    if (oDiff.TotalHours < 23.5) {
        span = Math.round(oDiff.TotalHours);
        uom = "hour";
    }
    else {
        span = Math.round(oDiff.TotalDays);
        uom = "day";
    }
}

if (span < 0) span = 0;

s = span + " " + uom;
if (span > 1) s += "s";
s += " ago";

return s;
}

答案 2 :(得分:0)

试试moment.js。对于任何与javascript相关的时间而言都很棒。

执行你的职能:

moment(time).fromNow();