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?

2
  • 1
    Convert the string to a number first? new Date(parseInt('1657756800000', 10)) Commented Jul 19, 2022 at 17:07
  • @evolutionxbox Yep that was it, I forgot to parseInt -.- Commented Jul 19, 2022 at 18:09

2 Answers 2

1

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));

Sign up to request clarification or add additional context in comments.

2 Comments

It was parseInt(), I forgot to parseInt() -.- Thank you!
No problem! I get small errors like that too and spend way too long trying to figure them out haha.
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
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.