ben tedder : code things

jQuery function for formatting dates in SharePoint with SPServices

I've been searching all over the web for this, and I can't find anything that works for me. So here's a small jQuery function I wrote that takes the default SharePoint date format (which looks like this: yyyy-mm-dd hh:mm:ss) and splits it all up and makes it useable.

The reason behind this issue is I'm using SPServices and jQuery Mobile to pull in date fields and display them in the browser in a much nicer way (like this).

How to use it:
In your SPServices call, you'll be calling a variable something like this:

startDate = $(this).attr("ows_Start_x0020_Date");

Then, we're going to send our new variable into the convertDate() function:

// to only get the date
convertDate(startDate, "date");
//to only get the time
convertDate(startDate, "time");

I split the date and time up because I'm always using start and end times, where the date is only secondary. So this way when you call the function you can specify which one you want. You could also get a full date this way:

convertDate(startDate, "date") + " " + convertDate(startDate, "time");

And here's the actual function:

function convertDate (x, formatter) {

    var months = ['January','February','March','April','May','June','July','August','September','October','November','December'];
    var shortMonths = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'];

    // split up date and time
    xDate = x.split(" ")[0];
    xTime = x.split(" ")[1];

    // split off the hour from the minute/second
    xMinSec = xTime.split(":")[1];
    xHour = xTime.split(":")[0];

    // set the am or pm suffix
    if (xHour > 12) {
        ampm = "pm";
        xHour -= 12;
    }  else if (xHour < 12){
        ampm = "am";
    } else {
        ampm = "pm";
    }
    //extract the minute from the minute/second
    xMin = xMinSec.split(":")[0];

    // split up the date into day, month (-1), and year
    xDay = xDate.split("-")[2];
    xMonth = shortMonths[xMonth = xDate.split("-")[1]-1];
    xYear = xDate.split("-")[0];

    // format your date as you like
    xFullDate = xMonth + " " + xDay + ", " + xYear;

    // format the time as you like
    xFullTime = xHour + ":" + xMin + ampm;

    // check the parameter to see which one to return
    if (formatter === "date") {
        return xFullDate;
    } else if (formatter === "time") {
        return xFullTime;
    }
}

Hope it works for you!