Ask Your Question
4

What is the process for extracting the month from date string "yyyy-mm-dd" or timeStamp in javascript?

asked 2021-09-23 11:00:00 +0000

scrum gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
2

answered 2022-03-24 17:00:00 +0000

david gravatar image

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.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2021-09-23 11:00:00 +0000

Seen: 7 times

Last updated: Mar 24 '22