Home > Mobile >  how to solve Invalid Date {} JavaScript
how to solve Invalid Date {} JavaScript

Time:02-20

when I try to get the year, the month and the time of a date, I get Invalid Date {}

const d = new Date();
let time = new Date(d.getFullYear(), d.getMonth(), d.getTime());
document.getElementById("demo").innerHTML = time;
<div id='demo'></div>

CodePudding user response:

new Date().getTime() returns the number of milliseconds that have elapsed since midnight on Jan 1, 1970, while new Date().getDay(), which is what you're looking for, returns the current day.

const d = new Date();
let time = new Date(d.getFullYear(), d.getMonth(), d.getDay());
document.getElementById("demo").innerHTML = time;
<div id='demo'></div>

CodePudding user response:

well here are pair of errors in your code working with the javascript Date object API. d.getFullYear() gives 2022 and this is correct, and d.getMonth() returns the months starting by 0 but as you are showing the object directly you don't need to worry about that, the problem surges when you call d.getTime() that returns:

A number representing the milliseconds elapsed between 1 January 1970 00:00:00 UTC and the given date.

MDN reference

So maybe what you are trying to do is this instead:

        const d = new Date();           
        let time = new Date(d.getFullYear(), d.getMonth(), d.getUTCDate());
        document.getElementById("demo").innerHTML = time;

CodePudding user response:

the month argument range from 0 to 11 in javasript, to get the correct month try (d.getMonth() 1).

const d = new Date();

//I don't need utc date I need to ge the date on that form: year, month, time

let time = d.getUTCFullYear()   ","  (d.getMonth() 1)   "," d.getTime();

console.log("time",time);
  • Related