mo_maat
mo_maat

Reputation: 2240

Javascript newdate function unexpected output

I am confused by the result of the following script and I don't understand why it is what it is:

enddate = '01-02-2020'; //euro format dd-mm-yyyy
datesplit = enddate.split("-"); 

console.log("datesplit: ", datesplit); //[ '01', '02', '2020' ]
console.log(datesplit[2]); // 2020
console.log(datesplit[1]); // 02
console.log(datesplit[0]); // 01

enddate1 = new Date(datesplit[2],datesplit[1],datesplit[0]);

console.log("enddate 1", enddate1); //output: 2020-03-01T05:00:00.000Z , but I'm expecting 2020-02-01T00:00:00.000Z

That last console log output is what I can't understand. I would appreciate an explanation of why the result is what it is.

Upvotes: 1

Views: 102

Answers (3)

pacanga
pacanga

Reputation: 416

You can check Mozilla Documentation

You will see that January is 0, February is 1, and so on. So that's how date works in JavaScript.

You need to convert your month value to Number and then make it "-1". So something like this:

new Date(datesplit[2], (parseInt(datesplit[1], 10) - 1), datesplit[0])

Upvotes: 0

Shiny
Shiny

Reputation: 5055

JavaScript treats the month as zero-based. So you'll have to -1 your month value to get the right result. As @RobG said, you should use new Date(Date.UTC(...)) to get your date in UTC

let endDate = '01-02-2020' // dd-mm-yyyy;
let [day, month, year] = endDate.split('-');

// Months are zero-based, so -1 to get the right month
month = month - 1;

console.log(day);  // '01'
console.log(month);// 1
console.log(year); // '2020'

let newDate = new Date(Date.UTC(year, month, day));

console.log(newDate) // "2020-02-01T00:00:00.000Z"

Upvotes: 5

Sherman Hui
Sherman Hui

Reputation: 998

Given that the other posts seem to have helped you get the right month, have you tried using .toISOString method on the Date object to get the right UTC offset?

The docs on MDN state that the timezone is always zero UTC offset.

Upvotes: 0

Related Questions