'counter with leading zeros not returning the right result
Whenever I click, I count from 01 to 10, 01 all the way to 09 works but when it reaches 10 it messes up the number.
I have a function that receives a year variable which is the last 2 numbers of a year ex: 2022, the year for that in my case would be 22. I want to then count from 01 to 10 without removing the leading zeros. My code works once it's larger than 10 but whenever it's at 9 and then hits 10, the year gets a 0 added. This is an example of what the result would look like : 2008, 2009, 20010. I'm not sure why this happens because I'm only going until 9 and then checking if it's equal to 10...
if (parseInt(strYear) < 10) {
location.href = 'calendar.htm?ddlDay=' + numDay + '&ddlMonth=' + numMonth +
'&ddlCentury=' + numCentury + '&ddlYear=0' + (parseInt(strYear) + 1)
}
else if (parseInt(strYear) == 10) {
location.href = 'calendar.htm?ddlDay=' + numDay + '&ddlMonth=' + numMonth +
'&ddlCentury=' + numCentury + '&ddlYear=' + parseInt(strYear)
}
else if (parseInt(strYear) > 10) {
location.href = 'calendar.htm?ddlDay=' + numDay + '&ddlMonth=' + numMonth +
'&ddlCentury=' + numCentury + '&ddlYear=' + (parseInt(strYear) + 1)
}
Solution 1:[1]
I think you can do that without those "if" conditions. Check the code below if that produces your desired output...
const numDay = 20; const numMonth = 12;
const numCentury = 20; const strYear = 22;
location.href = 'calendar.htm?ddlDay=' + numDay + '&ddlMonth=' + numMonth + '&ddlCentury=' + numCentury + '&ddlYear=' + numCentury + strYear.toString().padStart(2, '0');
Output: calendar.htm?ddlDay=20&ddlMonth=12&ddlCentury=20&ddlYear=2022
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Anas Abdullah Al |
