Jonathan Clark
Jonathan Clark

Reputation: 20538

Javascript. Pretty date with months and years

I got the below script to convert dates into pretty dates. It works perfectly fine but only to a level of weeks. I need it to work fine for months and perhaps years to.

How can I modify 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";
}

Upvotes: 3

Views: 3226

Answers (3)

Matt
Matt

Reputation: 442

Try moment.js. It's brilliant for anything time related in javascript.

To do your function:

moment(time).fromNow();

Upvotes: 0

Mark Schultheiss
Mark Schultheiss

Reputation: 34168

I would look at this: http://ejohn.org/blog/javascript-pretty-date/. Check the comments for some additional information.

See here: http://jsfiddle.net/MarkSchultheiss/cgMZz/1/

After a BIT more reading I see an update posted here: http://www.zachleat.com/web/yet-another-pretty-date-javascript/ and finally moved to: https://github.com/zachleat/Humane-Dates all credit to the coders!

Upvotes: 8

Todd H.
Todd H.

Reputation: 2562

I use a combination of a dateDiff extension for dates and this (toAge) extension:

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

Upvotes: 0

Related Questions