Reputation: 8521
I need a regex to pattern match the following -
mm/dd/yyyy
The following date entries should pass validation:
Also, after validating above regex
, what is the best way convert above date string
to Date
object?
Upvotes: 1
Views: 249
Reputation: 382514
You should do the check and the parsing in one go, using split, parseInt and the Date constructor :
function toDate(s) {
var t = s.split('/');
try {
if (t.length!=3) return null;
var d = parseInt(t[1],10);
var m = parseInt(t[0],10);
var y = parseInt(t[2],10);
if (d>0 && d<32 && m>0 && m<13) return new Date(y, m-1, d);
} catch (e){}
}
var date = toDate(somestring);
if (date) // ok
else // not ok
01/22/2012 ==> Sun Jan 22 2012 00:00:00 GMT+0100 (CET)
07/5/1972 ==> Wed Jul 05 1972 00:00:00 GMT+0100 (CEST)
999/99/1972 ==> invalid
As other answers of this page, this wouldn't choke for 31 in February. That's why for all serious purposes you should instead use a library like Datejs.
Upvotes: 1
Reputation: 66404
var dateStr = '01/01/1901',
dateObj = null,
dateReg = /^(?:0[1-9]|1[012]|[1-9])\/(?:[012][1-9]|3[01]|[1-9])\/(?:19|20)\d\d$/;
// 01 to 12 or 1 to 9 / 01 to 31 or 1 to 9 / 1900 to 2099
if( dateStr.match( dateReg ) ){
dateObj = new Date( dateStr ); // this will be in the local timezone
}
Upvotes: 0
Reputation: 1216
"/^(0?[1-9]|[12][0-9]|3[01])[\/\-](0?[1-9]|1[012])[\/\-]\d{4}$/"
link: Javascript date regex DD/MM/YYYY
Upvotes: 0