i’m trying to convert gen. 02, 2023
date in 2023-01-02
but my function formatDate:
function formatDate(date) {
var d = new Date(date),
month = '' + (d.getMonth() + 1),
day = '' + d.getDate(),
year = d.getFullYear();
if (month.length < 2)
month = '0' + month;
if (day.length < 2)
day = '0' + day;
return [year, month, day].join('-');
}
doesn’t seem to work properly.
Can you help me out?
It looks like i receive just NaN-NaN-NaN
as value.
2
Answers
You used
getMonth() method
to get the month number, but the month number iszero-based
. So, the month number for January is 0, not 1. You need to subtract 1 from the month number before you pass it to theformatDate() function.
Here is my version of this script:
But please note that is expecting that you will pass a string like ‘Jan. 02, 2023’ and it will return a string. If a detailed explanation is needed can provide as an update.