Athapali
Athapali

Reputation: 1089

Extract month, day and year from date regex

I have a date in "mm/dd/yyyy" format. But, depending on what day or month, there is no guarantee that the "mm/dd" part will necessarily have two digits. So the dates may be:

11/12/2014

or

6/12/2014

or

11/5/2014

In all of the above situations I will need to be able to extract each value for mm, dd, and yyyy so I can do something like this for a calculation:

Month = regex that returns month part.
Day = regex that returns day part
Year = regex that returns 4 digits year part.

This \d{2}/\d{2}/\d{2} matches the whole thing.

Upvotes: 3

Views: 31281

Answers (3)

Michał Miszczyszyn
Michał Miszczyszyn

Reputation: 12711

Regexp Solution

The proper regex matching all of your dates is: \d{1,2}/\d{1,2}/\d{4}. Notation {n,m} is called limiting repetition and in this case \d{n,m} means "between n and m digits (inclusive)". You can read more about that here: Limiting Repetition.

If you want to create matching groups, use "(" and ")" (parentheses). Addiitonally, in JavaScript, you have to to escape / with \ and thus your regexp is: /(\d{1,2})\/(\d{1,2})\/(\d{4})/

You can use exec function of the regexp to match strings against it. It returns an array containing the matched text as the first element and then one item for each of the matched groups.

You can find out more on MDN RegExp.prototype.exec or see this example below:

const datePattern = /(\d{1,2})\/(\d{1,2})\/(\d{4})/;
const date = datePattern.exec("11/12/2014"); // ["11/12/2014", "11", "12", "2014"]

Note: If an invalid string is passed (not matching the regular expression) exec function will return null. It's an easy way to do brief validation of users' input or data.

Alternative solution

Alternatively you can simply split the strings:

"11/12/2014".split('/'); // ["11", "12", "2014"]

But this will work regardless of what the string actually contains (it might contain string "ba/tm/an" and split will still return an array with three elements). For this reason, Regexp is probably a better fit if you want to validate the dates.

Upvotes: 10

Clint Powell
Clint Powell

Reputation: 2398

You don't need regex to extract the pieces, just use split. I used regex to allow forward or backward slashes.

var date = "1/10/2014"
, dateParts = date.split(/\\|\//)
, month = dateParts[0]
, day = dateParts[1]
, year = dateParts[2];

Upvotes: 0

Johan Karlsson
Johan Karlsson

Reputation: 6476

Try this:

var str = "11/6/2014";
var match = str.match(/(\d{1,2})\/(\d{1,2})\/(\d{4})/);

console.log(match[1]); // => "11"
console.log(match[2]); // => "6"
console.log(match[3]); // => "2014"

alternatively you can create a date object:

var date = new Date("11/6/2014");

var year = date.getFullYear();
var month = date.getMonth()+1;
var day = date.getDate();

console.log(year);  // => 2014
console.log(month); // => 11
console.log(day);   // => 6

Upvotes: 6

Related Questions