Does anyone know how to convert JS dateTime to MySQL datetime? Also is there a way to add a specific number of minutes to JS datetime and then pass it to MySQL datetime?
While JS does possess enough basic tools to do this, it's pretty clunky.
/**
* You first need to create a formatting function to pad numbers to two digits…
**/
function twoDigits(d) {
if(0 <= d && d < 10) return "0" + d.toString();
if(-10 < d && d < 0) return "-0" + (-1*d).toString();
return d.toString();
}
/**
* …and then create the method to output the date string as desired.
* Some people hate using prototypes this way, but if you are going
* to apply this to more than one Date object, having it as a prototype
* makes sense.
**/
Date.prototype.toMysqlFormat = function() {
return this.getUTCFullYear() + "-" + twoDigits(1 + this.getUTCMonth()) + "-" + twoDigits(this.getUTCDate()) + " " + twoDigits(this.getUTCHours()) + ":" + twoDigits(this.getUTCMinutes()) + ":" + twoDigits(this.getUTCSeconds());
};
How do you call a function like this with a variable?
@Catfish You mean with a specific date? You use a
Date
object.new Date().toMysqlFormat()
ornew Date(2014,12,14).toMysqlFormat()
or whatever.This answer had its day while JavaScript was old and clunky. If you target a modern browser, I recommend Gajus'
toISOString
approach.