#Why am I getting an incorrect date with the new Date() function in js?

7 messages · Page 1 of 1 (latest)

vernal egret
#

As per the image, the dateString and the timePieces are all as they should be except when I create a new Date() it incorrectly says it's a month in the future. I can't figure out why and if it's something I'm doing wrong and can correct before just continuing on and brute forcing the change with getTimezoneOffset.

Ultimately my end goal is to convert a bunch of elements on a webpage from UTC to the users local time without using any frameworks and this quirk is rather troublesome.

If anyone is able to help I greatly appreciate it, it's probably my own error somewhere I'm just too green to find it.

turbid gyro
#

Okay, I'm super curious. I ran it and it doesn't work for me either, I get the same result.

On the other hand, I noticed that you made your own string to test out your date functions with. new Date() can also take a string, and I think it would accept whatever string you're converting on the page.

If your goal is to convert a date string that looks more like the standard UTC format, I'd try just popping that string into the new date object and then you should just be able to add the time difference.

If your goal is to convert something that looks exactly like your test string, well you already picked out the part that's the hours, you could just add the time difference to the hours and reconstruct the time from the pieces.

#

Oh got, I figured out the answer to your original question, and it's shockingly painful.

Why is your date off by one month? Because they start counting the months at zero.

vernal egret
#

When I pop the string into the new Date() regardless of how it's formatted I'm getting an invalid date object and the only way I've gotten passed that is by the tedious solution. I haven't popped into VS to try it yet so supposedly to get the accurate date I just subtract 1 from the month and it'll fix things? Curious I couldn't find the same answer with google if it was really that easy.

turbid gyro
#

Yeah, I'm pretty sure it will!

I just played around with the date directly, and here's what you end up seeing:

year, month, date...
console.log(new Date(2022, 0, 10, 1, 0, 0))

Mon Jan 10 2022 01:00:00 GMT-0600 (Central Standard Time)

So month 0 is definitely January!

vernal egret
#

It's definitely working! Although now I notice the Date.UTC conversion isn't working properly, it seems to be assuming it's still my local time. I'll try and solve that on my own before checking back with discord though. Appreciate the assistance!

turbid gyro
#

No problem!