I’ve been working on a project to display data stored in a MySQL database using the Google Graph API. I’ve done this before, but this time I need to display the time the MySQL entry was created. The DB row contains this information as a MySQL timestamp field, and is returned as a string when I fetch it, for example:
To me, this seems pretty basic, and I really don’t understand why it was omitted from the language. There are a lot of libraries out there that will do this for you, but I ended up using jQuery, as I was already using it for the AJAX and graphing support.
jQuery provides the .datepicker class, which includes a date formatter. I just needed the month and day, the month needs to be a short string, while the day is a number without any leading zeros. I used the following:
Where utcTime is a Date object that’s been created from the MySQL string with:
var dt = new Date(Date.parse(item + "Z"));
At the time I did this, there is no option for handling Time within the standard jQuery package, so I added that manually, padding with a leading ‘0’ as needed, with the final date/time string being created with:
return $.datepicker.formatDate("M-d",utcTime) + " " + ("0" + utcTime.getHours()).slice(-2) + ":" + ("0" + utcTime.getMinutes()).slice(-2);
Note: I could have had .datepicker parse the string, but it wouldn’t have given me the time portion, so I do that in a separate step.