Convert a mySQL date to Javascript date

后端 未结 12 1821
没有蜡笔的小新
没有蜡笔的小新 2020-12-25 13:09

What would be the best way to convert a mysql date format date into a javascript Date object?

mySQL date format is \'YYYY-MM-DD\' (ISO Format).

12条回答
  •  滥情空心
    2020-12-25 14:04

    While JS does possess enough basic tools to do this, it's pretty simple to use

    /**
     * Ashu, You first need to create a formatting function to pad numbers to two digits…
     **/
    function twoDigits(d) {
        if(0 <= d && d < 10) return "0" + d.toString();
        if(-10 < d && d < 0) return "-0" + (-1*d).toString();
        return d.toString();
    }
    
    
    Date.prototype.toMysqlFormat = function() {
        return this.getUTCFullYear() + "-" + twoDigits(1 + this.getUTCMonth()) + "-" + twoDigits(this.getUTCDate()) + " " + twoDigits(this.getUTCHours()) + ":" + twoDigits(this.getUTCMinutes()) + ":" + twoDigits(this.getUTCSeconds());
    };
    
    
    var date = new Date();
    
    document.getElementById("date").innerHTML = date;
    document.getElementById("mysql_date").innerHTML = date.toMysqlFormat();
    console.log(date.toMysqlFormat());
    Simple date:
    Converted Mysql Fromat:

提交回复
热议问题