代码之家  ›  专栏  ›  技术社区  ›  BrynJ

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

  •  30
  • BrynJ  · 技术社区  · 16 年前

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

    12 回复  |  直到 16 年前
        1
  •  32
  •   T.J. Crowder    13 年前

    可能最好使用像这样的图书馆 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

    警告:我刚刚把它扔掉了,它完全没有经过测试。

        2
  •  145
  •   Afanasii Kurakin    7 年前

    去约会

    new Date().toJSON().slice(0, 10)
    //2015-07-23
    

    日期时间

    new Date().toJSON().slice(0, 19).replace('T', ' ')
    //2015-07-23 11:26:00
    

        3
  •  8
  •   Chris Mayhew    14 年前

    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);
    
        4
  •  7
  •   Community Mohan Dere    9 年前

    最短版本的 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'
    
        5
  •  7
  •   Arsen K. pastullo    8 年前
    function js2Sql(cDate) {
        return cDate.getFullYear()
               + '-'
               + ("0" + (cDate.getMonth()+1)).slice(-2)
               + '-'
               + ("0" + cDate.getDate()).slice(-2);
    }
    
        6
  •  5
  •   Jan Jůna    8 年前

    date.toISOString().split("T")[0]
    
        7
  •  3
  •   salonMonsters    16 年前

    在第一个例子中有点输入错误,当一天的长度小于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;
    }
    
        8
  •  3
  •   bortunac    10 年前

    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 + "....";
    
        9
  •  2
  •   Community Mohan Dere    9 年前

    我需要这个文件名和当前时区的时间。

    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
    

    来源

        10
  •  0
  •   JoseMarmolejos    16 年前

    查看这个方便的库,以满足您的所有日期格式设置需求: http://blog.stevenlevithan.com/archives/date-time-format

        11
  •  0
  •   cnizzardini    14 年前
    // 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()));
    
        12
  •  0
  •   Jason Sturges    13 年前

    可以是!

    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;
    }
    
        13
  •  0
  •   avimimoun    7 年前

    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表单中输入的datetime保持不变:不转换为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('-');
      }
    
        14
  •  0
  •   Bennybear    5 年前

    new Date().toISOString().replace('T', ' ').split('Z')[0];
    
    推荐文章