Haseena Parkar
Haseena Parkar

Reputation: 979

Regular expression to fetch year from date - Javascript

Can somebody please help me construct a regular expression in Javascript to check if year 2017 exists or a year starting with 19 or 20 (century) exists in a given date.

My date format is : Fri Dec 01 2017 00:00:00 GMT-0800 (Pacific Standard Time).

I tried this but it fails:

var str = "Fri Dec 01 2017 00:00:00 GMT-0800 (Pacific Standard Time)";
var patt = new RegExp("/^\S{3}[\s]\S{3}[\s]\d{2}[\s]\d{4}$/");
var res = patt.test(str);

Thanks, Haseena

Upvotes: 0

Views: 1136

Answers (4)

Tamilselvan
Tamilselvan

Reputation: 54

You can use Date.getFullYear() method.

var d = new Date("Fri Dec 01 1999 00:00:00 GMT-0800 (Pacific Standard Time)");
var year = d.getFullYear();

Upvotes: 3

Vince
Vince

Reputation: 4232

With a fixed date format, this is really easy:

First, just extract your year using a regular expression var year = str.match(/^.{11}(\d{4})/)[1]

.match returns an array where the first element is the entire matched string and subsequent elements are the parts captured in parentheses.

After you have this, you can test if year === '2017' or if year.substr(0, 2) === '19'.

There are about a dozen other ways to do this, too.

var myDate = 'Fri Dec 01 2017 00:00:00 GMT-0800 (Pacific Standard Time)';

function isCorrectYear(dateString) {
  var year = dateString.match(/^.{11}(\d{4})/)[1];
  if (year === '2017') return true;
}

if (isCorrectYear(myDate)) {
  alert("It's the correct year.");
}

Something just occurred to me... "year 2017 exists or a year starting with 19 or 20". Doesn't that cover every year in every date string you are ever likely to encounter? I don't think they had Javascript before the 1900s and I doubt anything any of us will write will still be in use after the year 2100.

Upvotes: -1

Mustofa Rizwan
Mustofa Rizwan

Reputation: 10466

The year validation with multiple condition is not quite a regex thingy

If I have understood your question then you can try this:

^[a-zA-Z]{3}\s+[A-Za-z]{3}\s+\d{2}\s+(2017|(?:19\d{2}|20\d{2}))\s+.*
  1. It will only match if the year is 2017
  2. It will match if the year starts with 19
  3. It will match if the year starts with 20
  4. If match is found, then the year can be found in group 1

Explanation

const regex = /^[a-zA-Z]{3}\s+[A-Za-z]{3}\s+\d{2}\s+(2017|(?:19\d{2}|20\d{2}))\s+.*$/gm;
const str = `Fri Dec 01 2017 00:00:00 GMT-0800 (Pacific Standard Time)`;
let m;

 if((m = regex.exec(str)) !== null) {
   console.log("Full match ="+m[0]);
   console.log("Matched year ="+m[1]);
}
else
  console.log("no match found");

Upvotes: 0

Jeffy Zhang
Jeffy Zhang

Reputation: 111

Here is example you can use.

var str="Fri Dec 01 2017 00:00:00 GMT-0800 (Pacific Standard Time)";
var patt=/(\w{3}\s){2}\d{2}\s(\d{4})\s(.*)/;
var results = patt.exec(str);
console.log(results);
console.log(results[2]);

The second group is match the year.

Upvotes: 0

Related Questions