Returning the day of the week

I am wondering if anyone can comment why sometimes i get return 6 and sometimes 0 for the day of the week

var date = new Date("2022-01-23");
console.log(date.getDay()); //returns 6

var date = new Date("2022-01-9");
console.log(date.getDay()); //returns 0

What do you get if you use

var date = new Date("2022-01-09");

?

i get 6

So when you do a 2-digit day, you get the timezone-adjusted timestamp from UTC. You’re somewhere west of the prime meridian, so you got a negative offset, as i do:

> new Date("2022-01-23")
< Sat Jan 22 2022 19:00:00 GMT-0500 (Eastern Standard Time)

Note that it gave me a timestamp that is 5 hours back - making it SATURDAY THE 22nd, not Sunday the 23rd.

If i put the 9th in as a 2-digit day, I get the same:

> new Date("2022-01-09");
< Sat Jan 08 2022 19:00:00 GMT-0500 (Eastern Standard Time)

If however, I put in a single-digit day, the Date constructor has to parse it differently (because standard format is a 2 digit day: YYYY-MM-DD), and so I get a Midnight Local timestamp, as opposed to a Midnight-UTC timestamp:

> new Date("2022-01-9");
< Sun Jan 09 2022 00:00:00 GMT-0500 (Eastern Standard Time)

And now it’s Sunday.

You can force a two-digit day to return a Local-Midnight timestamp by adding “00:00:00” at the end of the date:

> new Date("2022-01-23 00:00:00")
< Sun Jan 23 2022 00:00:00 GMT-0500 (Eastern Standard Time)

if you set your date as

new Date(“2022-01-23 14:25:22”)

how do you get

“2022-01-23”

as a String without time portion?

What I am actually trying to do is get a current date and find if that date is in this array

const holiday = [‘2023-10-09’,‘2023-12-25’'];

but since when I get current date using

let d = new Date()

depending on what machine this code runs this d comes with time as well and this code doesn’t work

d.toDateString()

What is the best way to get current date regardless what machine code runs and compare it to string items in my array?

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.