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

前端 未结 14 899
清歌不尽
清歌不尽 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: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()));
    

提交回复
热议问题