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

前端 未结 14 916
清歌不尽
清歌不尽 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:23

    Try this

    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(':');
      }
    

    Note that you can remove the hours, minutes and seconds and you will have the result as YYYY-MM-DD The advantage is that the datetime entered in the HTML form remains the same: no transformation into UTC

    The result will be (for your example) :

    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('-');
      }
    

提交回复
热议问题