Search code examples
javascriptdate-formatting

How to convert a Javascript Date String into a Javascript Date Object?


My query in JS is returning a Javascript date as a string from my database (i.e "/Date(1657756800000)/"). I need a way to first convert that into a Javascript date object and then parse/output it as a readable date string.

Currently if I strip the preceding "/Date(" and ending ")/" parts and try to just pass that number "1657756800000" into a "new Date(1657756800000)" I get an "Invalid Date" error.

How do I get around this?


Solution

  • Just do

    var timeStamp = 1657756800000;
    var yourDate = new Date(timeStamp);
    console.log(yourDate.toISOString());

    If you are still getting errors, it is likely you are passing a string to new Date(). To fix this, just do

    // your timestamp as a string
    var timeStamp = '1657756800000';
    // parseInt() converts numbers to strings
    var yourDate = new Date(parseInt(timeStamp));
    console.log(yourDate.toISOString());

    If you want your date formatted nicely, use toLocaleDateString and toLocaleTimeString in this function:

    function printFancyTime(dateObj) {
        return dateObj.toLocaleDateString() + " " + dateObj.toLocaleTimeString();
    }
    // your timestamp as a string
    var timeStamp = '1657756800000';
    // parseInt() converts numbers to strings
    var yourDate = new Date(parseInt(timeStamp));
    console.log(printFancyTime(yourDate));