Reputation: 3541
I'm using datatables.net jquery plugin and populating the data through asp.net mvc4.
One of my columns is a date format. I'm interested in changing the format of how it is displayed but not changing the type of the column from date to string.
I'm currently using default initialization:
$('#data-table').dataTable();
My 4th column is a date "Created Date" and is currently displayed as "7/07/2013 9:38:11 p.m." I would like it to be displayed as either "7/07/2013" or "7 Jul 2013".
I thought this was a relatively easy task but haven't been able to find the answer I'm after.
I'd like to avoid additional plugins if possible. Is there a simple way that I'm missing?
Upvotes: 5
Views: 15621
Reputation: 4587
Whether using a legacy version of the plugin or the latest, the render function is the way to go. From that point it becomes a question not so much of datatables (which doesn't do any formatting) and how to format a date in JavaScript.
For that, I'd recommend the excellent moment.js library (rock solid, ~30k stars on github, 100k+ unit tests; pretty much the go-to for dealing with time in js).
Upvotes: 0
Reputation: 5663
If you are using a nullable DateTime? you'll want to use a different rendering function:
$('#users-tbl').DataTable({
columns: [
{ "data": "ID", "visible" : false},
{"data": "MyDateField",
"type": "date ",
"render":function (value) {
if (value === null) return "";
var pattern = /Date\(([^)]+)\)/;
var results = pattern.exec(value);
var dt = new Date(parseFloat(results[1]));
return (dt.getMonth() + 1) + "/" + dt.getDate() + "/" + dt.getFullYear();}
}
]};
Upvotes: 0
Reputation: 3541
Here is what I came up with. Using how it renders I can manipulate the way the date is displayed to anyway I want.
$('#data-table').dataTable({
"aoColumnDefs": [
{
"aTargets": [0],
"bSearchable": false,
"sType": 'date',
"fnRender": function ( oObj ) {
var javascriptDate = new Date(oObj.aData[0]);
javascriptDate = javascriptDate.getDate()+"/"+(javascriptDate.getMonth()+1)+"/"+javascriptDate.getFullYear();
return "<div class='date'>"+javascriptDate+"<div>";
}
}
]
});
I hope this will be useful to others...
Upvotes: 15