I was trying to add a number of years to a Date in JavaScript.
Should be easy except I forgot the cardinal rule of accepting user input: check it!
I was getting the number of years as an ‘integer’ via an API, but of course it turned out to be a string that looked like an integer.
$letd1=newDate(2021,07,12);undefined$letyears=2;undefined$letyears_string="2";undefined$d1.getFullYear()+years;2023// Expected...
$d1.getFullYear()+years_string;"20212"// Oh brother...
$letd2=newDate(d1);undefined$d2.getFullYear();2021$d2.setFullYear(d2.getFullYear()+years);1691820000000$d2DateSatAug12202300:00:00GMT-0600(MountainDaylightTime)$d3=newDate(d1);DateThuAug12202100:00:00GMT-0600(MountainDaylightTime)$d3.setFullYear(d3.getFullYear()+years_string);575681234400000// Yeah, the math breaks...
$d3DateWedAug122021200:00:00GMT-0600(MountainDaylightTime)// wait...the year 20212?!
It’s embarrassing how long it took me to spot that extra digit on the year!
How did I solve this issue?
A simple conversion fixed it: