I\'m trying to use javascript to convert a date object into a valid mysql date - what is the best way to do this?
function js2Sql(cDate) {
return cDate.getFullYear()
+ '-'
+ ("0" + (cDate.getMonth()+1)).slice(-2)
+ '-'
+ ("0" + cDate.getDate()).slice(-2);
}
// function
getDate = function(dateObj){
var day = dateObj.getDay() < 9 ? '0'+dateObj.getDay():dateObj.getDay();
var month = dateObj.getMonth() < 9 ? '0'+dateObj.getMonth():dateObj.getMonth();
return dateObj.getFullYear()+'-'+month+'-'+day;
}
// example usage
console.log(getDate(new Date()));
// with custom date
console.log(getDate(new Date(2012,dateObj.getMonth()-30,dateObj.getDay()));
just this :
Object.defineProperties( Date.prototype ,{
date:{
get:function(){return this.toISOString().split('T')[0];}
},
time:{
get:function(){return this.toTimeString().match(/\d{2}:\d{2}:\d{2}/)[0];}
},
datetime:{
get : function(){return this.date+" "+this.time}
}
});
now you can use
sql_query = "...." + (new Date).datetime + "....";
I'd like to say that this is likely the best way of going about it. Just confirmed that it works:
new Date().toISOString().replace('T', ' ').split('Z')[0];
The shortest version of https://stackoverflow.com/a/11453710/3777994:
/**
* MySQL date
* @param {Date} [date] Optional date object
* @returns {string}
*/
function mysqlDate(date){
date = date || new Date();
return date.toISOString().split('T')[0];
}
Using:
var date = mysqlDate(); //'2014-12-05'
This worked for me, just edit the string instead:
var myDate = new Date();
var myDate_string = myDate.toISOString();
var myDate_string = myDate_string.replace("T"," ");
var myDate_string = myDate_string.substring(0, myDate_string.length - 5);