Bry*_*ynJ 35 javascript mysql date
我正在尝试使用javascript将日期对象转换为有效的mysql日期 - 这样做的最佳方法是什么?
Afa*_*kin 124
要约会
new Date().toJSON().slice(0, 10)
//2015-07-23
Run Code Online (Sandbox Code Playgroud)
为datetime
new Date().toJSON().slice(0, 19).replace('T', ' ')
//2015-07-23 11:26:00
Run Code Online (Sandbox Code Playgroud)
请注意,生成的日期/日期时间始终为UTC时区
T.J*_*der 32
可能最好使用像Date.js这样的库(虽然没有多年维护)或Moment.js.
但是,做手工,你可以用Date#getFullYear(),Date#getMonth()(它从0开始=一月,所以你可能想+ 1)和Date#getDate()(月日).只需将月份和日期填充为两个字符,例如:
(function() {
Date.prototype.toYMD = Date_toYMD;
function Date_toYMD() {
var year, month, day;
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;
}
return year + "-" + month + "-" + day;
}
})();
Run Code Online (Sandbox Code Playgroud)
用法:
var dt = new Date();
var str = dt.toYMD();
Run Code Online (Sandbox Code Playgroud)
请注意,该函数有一个名称,这对于调试很有用,但由于匿名作用域功能,不会污染全局名称空间.
这使用当地时间; 对于UTC,只需使用UTC版本(getUTCFullYear等).
警告:我刚把它扔出去,它完全没有经过考验.
/sf/answers/801759731/的最短版本:
/**
* MySQL date
* @param {Date} [date] Optional date object
* @returns {string}
*/
function mysqlDate(date){
date = date || new Date();
return date.toISOString().split('T')[0];
}
Run Code Online (Sandbox Code Playgroud)
使用:
var date = mysqlDate(); //'2014-12-05'
Run Code Online (Sandbox Code Playgroud)
小智 7
function js2Sql(cDate) {
return cDate.getFullYear()
+ '-'
+ ("0" + (cDate.getMonth()+1)).slice(-2)
+ '-'
+ ("0" + cDate.getDate()).slice(-2);
}
Run Code Online (Sandbox Code Playgroud)
小智 7
这对我有用,只需编辑字符串:
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);
Run Code Online (Sandbox Code Playgroud)
从 JS 日期到 Mysql 日期格式转换你可以简单地这样做:
date.toISOString().split("T")[0]
Run Code Online (Sandbox Code Playgroud)