Convert a mySQL date to Javascript date

后端 未结 12 1794
没有蜡笔的小新
没有蜡笔的小新 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 13:59

    The shortest and fast method:

    var mySQLDate = '2015-04-29 10:29:08';
    new Date(Date.parse(mySQLDate.replace(/-/g, '/')));
    
    0 讨论(0)
  • 2020-12-25 14:02

    UNIX timestamp (milliseconds since the January 1, 1970) would be my preferred choice.

    You can pass it around as an integer and use the JS setTime() method to make a JS Date object from it.

    0 讨论(0)
  • 2020-12-25 14:02

    TypeScript with proper typing (no implicit string/int conversation):

    /**
     * @example
     * mysql_date_to_js_date("2019-12-31");
     */
    export function mysql_date_to_js_date(mysql_date: string) {
        var parts = mysql_date.split("-");
        if (parts.length != 3) {
            return undefined;
        }
        var year = parseInt(parts[0]);
        var month = parseInt(parts[1]) - 1; // months indexes are zero based, e.g. 9 == Octobre
        var day = parseInt(parts[2]);
        return new Date(year, month, day);
    }
    
    0 讨论(0)
  • 2020-12-25 14:03

    Stumbled on this looking to do exactly what the OP wanted, and used jhurshman answer so I +1'ed it, but it is incomplete as it will use 00:00:00 GMT-0500 (CDT) for the time part as it is not passed to the date object (var jsDate).

    In case anyone else is looking to create the full Javascript date object

    ex:

    Sat Mar 29 2014 23:24:28 GMT-0500 (CDT)
    

    Based on a MySQL DATETIME format

    ex:

    '9999-12-31 23:59:59'.
    

    You will want to use the following:

    var dateParts = isoFormatDateString.split("-");
    var jsDate = new Date(dateParts[0], dateParts[1] - 1, dateParts[2].substr(0, 2), dateParts[2].substr(3, 2), dateParts[2].substr(6, 2), dateParts[2].substr(9, 2));
    

    It will return in the browsers current timezone as you are creating the date object, but I would do the timezone conversion on the backend in most cases.

    0 讨论(0)
  • 2020-12-25 14:04

    Given your clarification that you cannot change the format of the incoming date, you need something like this:

    var dateParts = isoFormatDateString.split("-");
    var jsDate = new Date(dateParts[0], dateParts[1] - 1, dateParts[2].substr(0,2));
    

    Original response:

    Is there a reason you can't get a timestamp instead of the date string? This would be done by something like:

     SELECT UNIX_TIMESTAMP(date) AS epoch_time FROM table;
    

    Then get the epoch_time into JavaScript, and it's a simple matter of:

    var myDate = new Date(epoch_time * 1000);
    

    The multiplying by 1000 is because JavaScript takes milliseconds, and UNIX_TIMESTAMP gives seconds.

    0 讨论(0)
  • 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:<div id="date"></div>
    
    Converted Mysql Fromat: <div id="mysql_date"></div>

    0 讨论(0)
提交回复
热议问题