Monday, January 30, 2012

Dealing with .Net Date format issues in javascript

I've started a new job doing primarily web development. One thing I've been having to do is create a last updated message along the lines of "last updated x hours ago". My current web application is using Wcf Web Api (its really cool by the way). One issue that I've run into is microsoft's chosen format for date/time. It basically looks like this /Date(xxxxxxxxxxxxx-xxxx)/. Lovely isn't it? This format is the millisecond format for displaying the date in milliseconds. Suffice it to say that standard javascript methods like getTime() don't work with this format due to the additional "-xxxx" at the end. So here's a javascript method that does the job, enjoy.

 function getFormattedLastDateString(dateInput) {
    // setup last used date
    var lastModifiedMsg;
    var milliSecondsInOneDay = 24 * 60 * 60 * 1000;
    var milliSecondsInOneHour = 1 * 60 * 60 * 1000;
    var today = new Date();
    var created = dateInput.replace(/[-]{1}[0-9]{4}/, "");
    created = created.replace(/\/Date\(/, "");
    created = created.replace(/\)\//, "");
    console.log("created: " + created);
    console.log("today: " + today.getTime());
    var daysDiff = Math.round(Math.abs(today.getTime() - created) / milliSecondsInOneDay);
    if (daysDiff <= 1) {
        var hoursDiff = Math.round(Math.abs(today.getTime() - created) / milliSecondsInOneHour);
        if (hoursDiff != 1) {
            lastModifiedMsg = "updated " + hoursDiff + " hours ago.";
        }
        else {
            lastModifiedMsg = "updated " + hoursDiff + " hour ago.";
        }
    }
    else {
        if (daysDiff != 1) {
            lastModifiedMsg = "updated " + daysDiff + " days ago.";
        }
        else {
            lastModifiedMsg = "updated " + daysDiff + " day ago.";
        }
    }
    return lastModifiedMsg;
}

No comments:

Post a Comment