Javascript Pretty dates with months and years

I got below script to convert dates to beautiful dates. It works great fine, but only to the level of weeks. I need it to work perfectly for months and possibly years.

How can I change this code to work?

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
source share
3 answers

dateDiff (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;
}
0

Try moment.js . This is brilliant for any time related to javascript.

To fulfill its function:

moment(time).fromNow();
0
source

All Articles