0

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?

pass341
  • 13
  • 2

2 Answers2

0

Through an invoked function we do that:

df = (function(d) {
    d = new Date(d);
    return {
        date: d.getDate(),
        month: d.getMonth(),
        year: d.getFullYear(),
        hour: d.getHours(),
        minute: d.getMinutes(),
        second: d.getSeconds()
    }
});

console.log(df(1657756800000));

output

{
   date: 14,
   hour: 5,
   minute: 30,
   month: 6,
   second: 0,
   year: 2022
}
Art Bindu
  • 769
  • 4
  • 14
0

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));
Pufferfishe
  • 139
  • 1
  • 7