1

In javascript the date object give me following string.

var dateString=new Date();
console.log(dateString);//logs this 'Mon Jul 13 2015 00:00:00 GMT+0530 (India Standard Time)'

Is there any regular expression to validate a string which is of this date format? I am new to javascript please help.

4
  • 1
    Why would you need to validate the string? Commented Jul 1, 2015 at 9:16
  • I think Date.parse() will be a correct way to parse that string. Commented Jul 1, 2015 at 9:16
  • My advice is that you don't even try. Dates are hard. There're libraries for that. Commented Jul 1, 2015 at 9:18
  • /^(?:Mon|Tue|Wed|Thu|Fri|Sat|Sun) (?:Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) (?:[0-2][0-9]|3[01]) \d{4} (?:[01][0-9]|2[0-3]):[012345][0-9]:[012345][0-9] GMT\+0530 \(India Standard Time\)$/ Not true validation though, and you have said what you mean by validate. Commented Jul 1, 2015 at 9:24

1 Answer 1

1

You can use Date.parse() to test the string:

function isDate(str){ return !isNaN( Date.parse( str ) ); }

Testing:

isDate( 'Mon Jul 13 2015 00:00:00 GMT+0530 (India Standard Time)' ); // true
isDate( '' ); // false
isDate( 1 ); // false

isDate( '2015-07-01' ); // true
isDate( '1 July 2015' ); // true
isDate( '1st July 2015' ); // false

// ISO 8601 Dates:
isDate( '2015-07-01T12:30:50' ) // true
isDate( '2015-07-01T12:30:50Z' ); // true 
isDate( '2015-07-01T12:30:50+01:00' ); // true 
isDate( '2015-07-01T12:30:50-01:00' ); // true
isDate( '2015-07-01 12:30:50' ) // false 
isDate( '2015-07-01T12:30:50+1:00' ); // false
Sign up to request clarification or add additional context in comments.

2 Comments

On further testing, Date.parse( 'abc-12345' ); returns NaN on Firefox, IE9 and IE11 but returns the date 12345-01-01T00:00:00Z on Chrome (and Node.js) so there is inconsistencies in their date handling.
Anyway I changed my approach of dealing with dates. Thanks a ton for your help.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.