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

04.08.2008
| 9080 views |
  • submit to reddit
        As of <a href="http://developer.yahoo.com/yui/">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="http://www.datejs.com/">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 datejs.com'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);