There are multiple ways to extract the month from a date string or timestamp in JavaScript:
const dateStr = "2022-04-28";
const month = new Date(dateStr).getMonth() + 1; // adding 1 to get the actual month value
console.log(month); // Output: 4
const dateStr = "2022-04-28";
const month = dateStr.split("-")[1];
console.log(month); // Output: 04
const dateStr = "2022-04-28";
const regex = /-(\d{2})-/;
const month = dateStr.match(regex)[1];
console.log(month); // Output: 04
Note: In all of the above techniques, make sure to add 1 to the final value if you want to get the actual month number (1-12) instead of 0-11.
Asked: 2021-09-23 11:00:00 +0000
Seen: 7 times
Last updated: Mar 24 '22