将 javascript 到日期对象转换为 mysql 日期格式 (YYYY-MM-DD)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2280104/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-22 23:35:29  来源:igfitidea点击:

Convert javascript to date object to mysql date format (YYYY-MM-DD)

javascriptmysqldate

提问by BrynJ

I'm trying to use javascript to convert a date object into a valid mysql date - what is the best way to do this?

我正在尝试使用 javascript 将日期对象转换为有效的 mysql 日期 - 最好的方法是什么?

采纳答案by T.J. Crowder

Probably best to use a library like Date.js(although that hasn't been maintained in years) or Moment.js.

可能最好使用像Date.js(尽管已经多年没有维护)或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, e.g.:

但是要手动完成,您可以使用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;
    }
})();

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.).

使用当地时间;对于 UTC,只需使用 UTC 版本(getUTCFullYear等)。

Caveat: I just threw that out, it's completely untested.

警告:我只是把它扔掉了,它完全未经测试。

回答by Afanasii Kurakin

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

请注意,生成的日期/日期时间将始终位于 UTC 时区

回答by KMT

function js2Sql(cDate) {
    return cDate.getFullYear()
           + '-'
           + ("0" + (cDate.getMonth()+1)).slice(-2)
           + '-'
           + ("0" + cDate.getDate()).slice(-2);
}

回答by Chris Mayhew

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);

回答by Vitaly Sivkov

The shortest version of https://stackoverflow.com/a/11453710/3777994:

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'

回答by bortunac

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 + "....";

回答by salonMonsters

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.

在第一个示例中有点打字错误,当一天的长度小于 1 时,它会将月份而不是日期添加到结果中。

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;
}

回答by Jan J?na

From JS date to Mysql date format conversion you can simply do this:

从 JS 日期到 Mysql 日期格式转换你可以简单地这样做:

date.toISOString().split("T")[0]

回答by blablabla

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

Source

来源

回答by Samuel Peixoto

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;
}