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

前端 未结 14 884
清歌不尽
清歌不尽 2020-12-13 18:04

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

相关标签:
14条回答
  • 2020-12-13 18:26
    function js2Sql(cDate) {
        return cDate.getFullYear()
               + '-'
               + ("0" + (cDate.getMonth()+1)).slice(-2)
               + '-'
               + ("0" + cDate.getDate()).slice(-2);
    }
    
    0 讨论(0)
  • 2020-12-13 18:28
    // 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()));
    
    0 讨论(0)
  • 2020-12-13 18:29

    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 + "....";
    
    0 讨论(0)
  • 2020-12-13 18:32

    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];
    
    0 讨论(0)
  • 2020-12-13 18:33

    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'
    
    0 讨论(0)
  • 2020-12-13 18:39

    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);
    
    0 讨论(0)
提交回复
热议问题