1

When I have a date preloaded into my date picker and then manually change the year, it alters the rest of the date. My guess is that new Date() is having a hard time reading the input.

default string within the input (not an instance of Date):

 2021-09-09

date after conversion using new Date()

Thu Sep 09 2021 00:00:00 GMT-0400 (Eastern Daylight Time)

This is all correct so far

Here I manually enter the number 2 in the year portion of the html input string

0002-09-09

date

 Mon Feb 09 2009 00:00:00 GMT-0500 (Eastern Standard Time)

It changed from Sept 9th 2021 to Feb 9th 2009. Clearly the date object is having trouble figuring out the 0002 part of the date string but I am not sure why. What I expect the date to be is Sept 9th 0002 within the date picker (09/09/0002) so I can further add the digits I want to fill out the year.

In terms of my code I am simply passing in the new date string to the date object onChange. The replace is done to fix timezone issues with the day (the issue where the day will be one day off from the chosen date using the date-picker)

const date = new Date(string.replace(/-/g, '/').replace(/T.+/, ''))

1 Answers1

0

Why not simply leave the variable string as it is?

Instead of using new Date("0002/09/09"), use new Date("0002-09-09") - it works perfectly fine and delivers the desired result. Thus your replacement-method on the string is absolutely obsolete.

In your current code, the year gets mistaken for the month, that's why February 9th 2002 gets returned.

Bialomazur
  • 1,122
  • 2
  • 7
  • 18
  • The issue is when I don't replace the dashes I get a time zone issue. It also auto-clears the input setting it to mm/dd/yyyy (when applying your answer) https://stackoverflow.com/questions/7556591/is-the-javascript-date-object-always-one-day-off – helper12345 Sep 09 '21 at 13:02
  • input 0002-09-09 output from .getFullYear() = 2021 This is when I don't replace the - with / – helper12345 Sep 09 '21 at 13:16
  • @helper12345 OK - thanks for the info, I'll adapt my answer to it. – Bialomazur Sep 09 '21 at 13:16