Beware this content is over 5 years old and considered stale. It may no longer be accurate and/or reflect the understanding of the author but remains here for reference only. Please keep this in mind as you use this content.

Just a quick snippet that I wanted to keep in case I ever need it. And also because I’ve not posted an update here in quite some time.

I simply needed a way to pass a date time value from the client-side to the database and needed formatted in such a way that it could be used within a MySQL query.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
(function() {
Date.prototype.getMySQL = getMySQLDateTime;
function getMySQLDateTime() {
var year, month, day, hours, minutes, seconds;
year = String(this.getFullYear());
month = String(this.getMonth() + 1);
if (month.length == 1) {
month = "0" + month;
}
day = String(this.getDate());
if (day.length == 1) {
day = "0" + day;
}
hours = String(this.getHours());
if (hours.length == 1) {
hours = "0" + hours;
}
minutes = String(this.getMinutes());
if (minutes.length == 1) {
minutes = "0" + minutes;
}
seconds = String(this.getSeconds());
if (seconds.length == 1) {
seconds = "0" + seconds;
}
// should return something like: 2011-06-16 13:36:00
return year + "-" + month + "-" + day + ' ' + hours + ':' + minutes + ':' + seconds;
}
})();

Usage would be something like this:

1
2
var dt = new Date();
var mysql = dt.getMySQL();

Thanks to this post on StackOverflow.

If you have any amendments or samples where you’ve used the snippet, be sure to say so in the comments!