I need to get the year and month in JavaScript in a specific format, but cannot figure out how. I need it like this:
2022-03
I've tried using these functions but I need the 0 in the month:
console.log(new Date().getFullYear())
console.log(new Date().getMonth() + 1)
but the result is 2022 and 3
How can I format dates in javascript?
You can do something like this, append leading zero to date and slice last two digits
let d = new Date();
date = [
d.getFullYear(),
('0' + (d.getMonth() + 1)).slice(-2)
].join('-');
console.log(date)