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.

Hitesh Kumar
  • 3,508
  • 7
  • 40
  • 71
  • 1
    Why would you need to validate the string? – moffeltje Jul 01 '15 at 09:16
  • I think [`Date.parse()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/parse) will be a correct way to parse that string. – Wiktor Stribiżew Jul 01 '15 at 09:16
  • My advice is that you don't even try. Dates are hard. There're libraries for that. – Álvaro González Jul 01 '15 at 09: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`. – Xotic750 Jul 01 '15 at 09:24

1 Answers1

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
MT0
  • 143,790
  • 11
  • 59
  • 117
  • 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. – MT0 Jul 01 '15 at 10:19
  • Anyway I changed my approach of dealing with dates. Thanks a ton for your help. – Hitesh Kumar Jul 01 '15 at 10:30