我正在尝试使用 javascript 将日期对象转换为有效的 mysql 日期 - 最好的方法是什么?
To get date
new Date().toJSON().slice(0, 10)
//2015-07-23
for datetime
new Date().toJSON().slice(0, 19).replace('T', ' ')
//2015-07-23 11:26:00
Note, that resulting date / datetime will always be in UTC timezone
Probably best to use a library like Date.js (although that hasn't been maintained in years) or Moment.js .
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, eg:
(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;
}
})();
Usage:
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.
That uses local time; for UTC, just use the UTC versions ( getUTCFullYear
, etc.).
Caveat: I just threw that out, it's completely untested.
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);
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'
function js2Sql(cDate) {
return cDate.getFullYear()
+ '-'
+ ("0" + (cDate.getMonth()+1)).slice(-2)
+ '-'
+ ("0" + cDate.getDate()).slice(-2);
}
从 JS 日期到 Mysql 日期格式转换你可以简单地这样做:
date.toISOString().split("T")[0]
A bit of a typo in the first example, when a day has a length less than 1 it is adding the month instead of the day to the result.
Works great though if you change:
if (day.length == 1) {
day = "0" + month;
}
to
if (day.length == 1) {
day = "0" + day;
}
Thanks for posting that script.
The corrected function looks like:
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;
}
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 needed this for a filename and with the time in the current timezone.
const timezoneOffset = (new Date()).getTimezoneOffset() * 60000;
const date = (new Date(Date.now() - timezoneOffset))
.toISOString()
.substring(0, 19)
.replace('T', '') // replace T with a space
.replace(/ /g, "_") // replace spaces with an underscore
.replace(/\:/g, "."); // replace colons with a dot
// 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()));
看看这个方便的库以满足您所有的日期格式需求: http : //blog.stevenlevithan.com/archives/date-time-format
Try this
dateTimeToMYSQL(datx) {
var d = new Date(datx),
month = '' + (d.getMonth() + 1),
day = d.getDate().toString(),
year = d.getFullYear(),
hours = d.getHours().toString(),
minutes = d.getMinutes().toString(),
secs = d.getSeconds().toString();
if (month.length < 2) month = '0' + month;
if (day.length < 2) day = '0' + day;
if (hours.length < 2) hours = '0' + hours;
if (minutes.length < 2) minutes = '0' + minutes;
if (secs.length < 2) secs = '0' + secs;
return [year, month, day].join('-') + ' ' + [hours, minutes, secs].join(':');
}
Note that you can remove the hours, minutes and seconds and you will have the result as YYYY-MM-DD The advantage is that the datetime entered in the HTML form remains the same: no transformation into UTC
The result will be (for your example) :
dateToMYSQL(datx) {
var d = new Date(datx),
month = '' + (d.getMonth() + 1),
day = d.getDate().toString(),
year = d.getFullYear();
if (month.length < 2) month = '0' + month;
if (day.length < 2) day = '0' + day;
return [year, month, day].join('-');
}
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];
Can be!
function Date_toYMD(d)
{
var year, month, day;
year = String(d.getFullYear());
month = String(d.getMonth() + 1);
if (month.length == 1) {
month = "0" + month;
}
day = String(d.getDate());
if (day.length == 1) {
day = "0" + day;
}
return year + "-" + month + "-" + day;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.