[英]Convert javascript to date object to mysql date format (YYYY-MM-DD)
我正在嘗試使用 javascript 將日期對象轉換為有效的 mysql 日期 - 最好的方法是什么?
獲取日期
new Date().toJSON().slice(0, 10)
//2015-07-23
日期時間
new Date().toJSON().slice(0, 19).replace('T', ' ')
//2015-07-23 11:26:00
請注意,生成的日期/日期時間將始終位於 UTC 時區
可能最好使用像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;
}
})();
用法:
var dt = new Date();
var str = dt.toYMD();
請注意,該函數有一個名稱,這對於調試目的很有用,但由於匿名作用域函數,因此不會污染全局命名空間。
使用當地時間; 對於 UTC,只需使用 UTC 版本( getUTCFullYear
等)。
警告:我只是把它扔掉了,它完全未經測試。
這對我有用,只需編輯字符串:
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);
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];
}
使用:
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]
在第一個示例中有點打字錯誤,當一天的長度小於 1 時,它會將月份而不是日期添加到結果中。
但是如果你改變,效果很好:
if (day.length == 1) {
day = "0" + month;
}
到
if (day.length == 1) {
day = "0" + day;
}
感謝您發布該腳本。
修正后的函數如下所示:
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;
}
只是這個 :
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}
}
});
現在你可以使用
sql_query = "...." + (new Date).datetime + "....";
我需要這個文件名和當前時區的時間。
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
嘗試這個
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(':');
}
請注意,您可以刪除小時、分鍾和秒,結果將是 YYYY-MM-DD 優點是在 HTML 表單中輸入的日期時間保持不變:沒有轉換為 UTC
結果將是(對於您的示例):
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('-');
}
我想說這可能是最好的處理方式。 剛剛確認它有效:
new Date().toISOString().replace('T', ' ').split('Z')[0];
可!
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;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.