Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

There are multiple ways to extract the month from a date string or timestamp in JavaScript:

  1. Using the Date() object:
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
  1. Using the split() method:
const dateStr = "2022-04-28";
const month = dateStr.split("-")[1];
console.log(month); // Output: 04
  1. Using regular expressions:
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.