DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Snippets has posted 5883 posts at DZone. View Full User Profile

YUI DataTable - Understanding ISO / SQL Date Time Formats

  • submit to reddit
        As of <a href="">YUI</a> 2.5.1 the DataSource utility (which feeds the DataTable widget) only accepts either native Javascript Date objects or a string formatted to the North American locale (mm/dd/yyyyy) when using parser: "date" in your schema.

This can cause problems outside the USA, particularly if you are using ISO date formats say from MySQL DateTime columns. So let's fix this and include a Calendar widget for editing.

First, we depend on <a href="">Datejs</a> so ensure you've already got this loaded into the application. Next you need a couple of custom callback methods

 * Accepts a date string in any format that's library can recognise.
 * Returns a Date object if successful, false otherwise
parseSQLDate = function(data)
       var date = null;
       try {date = Date.parse(data);return date;}
       catch(e) {return false;}
 * This is a formatting callback for YUI DataTable to present date in ISO format
 * instead of American mm/dd/yyyy
formatDateInDataTable = function(elCell, oRecord, oColumn, oData)
       var oDate = oData;
       elCell.innerHTML = oDate.toString('yyyy-MM-dd');

Now to activate modify your schema thus:

dataSource.responseSchema = {
       resultsList: "items",
       fields: [{key: "created_on", parser: parseSQLDate}]

And in your columnDefs:

dataSource.columnDefs = [
       {key: "created_on", label: "Created", editor: "date", formatter: formatDateInDataTable}

Lastly we set up an editor for cells:

dataTable.subscribe("cellClickEvent", dataTable.onEventShowCellEditor);