将javascript转换为日期对象到mysql日期格式(YYYY-MM-DD) [英] Convert javascript to date object to mysql date format (YYYY-MM-DD)
问题描述
我正在尝试使用javascript将日期对象转换为有效的mysql日期 - 这是最好的方法是什么?
I'm trying to use javascript to convert a date object into a valid mysql date - what is the best way to do this?
推荐答案
最好使用像 Date.js 这样的图书馆(虽然没有维护年)或 Moment.js 。
Probably best to use a library like Date.js (although that hasn't been maintained in years) or Moment.js.
但要做到手动,你可以使用 Date#getFullYear()
, Date#getMonth()
(以0 =所以你可能想要+ 1)和 Date#getDate()
(月的日期)。只需填写月份和日期到两个字符,例如:
But to do it manually, you can use Date#getFullYear()
, Date#getMonth()
(it starts with 0 = January, so you probably want + 1), and Date#getDate()
(day of month). Just pad out the month and day to two characters, e.g.:
(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;
}
})();
用法:
var dt = new Date();
var str = dt.toYMD();
请注意,该函数有一个名称,这对于调试目的很有用,但是由于匿名范围功能没有污染全球命名空间。
Note that the function has a name, which is useful for debugging purposes, but because of the anonymous scoping function there's no pollution of the global namespace.
使用本地时间;对于UTC,只需使用UTC版本( getUTCFullYear
等)。
That uses local time; for UTC, just use the UTC versions (getUTCFullYear
, etc.).
警告:我刚刚抛出,这完全未经测试。
Caveat: I just threw that out, it's completely untested.
这篇关于将javascript转换为日期对象到mysql日期格式(YYYY-MM-DD)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!