-3

Regex date pattern yyyy-mm-dd javascript in java script, to compare from and to dates in the form, need to check To date is beyond the from date and dates should not the same ?

2 Answers2

4

You don't need any regular-expressions, you can use Date.parse to read-in ISO-8061 formatted dates and compare them directly:

var date1 = Date.parse("2015-12-14");
var date2 = Date.parse("2015-12-15");
return date1 < date2; // true

Note that Date.parse actually returns an integer value. It returns NaN if the string could not be parsed as a date.

Use the Date(string) constructor to get an actual Date instance:

var date1 = new Date("2015-12-14");
var date2 = new Date("2015-12-15");
return date1 < date2; // true

...however the Date(string) constructor will throw an exception on invalid input, so if you need to test a date first, do this:

var isValidDate = !isNaN( Date.parse( dateString ) );
if( isValidDate ) return new Date( dateString );

Or if you're feeling very efficient and want to avoid parsing the string twice:

var timestamp = Date.parse( dateString );
if( !isNaN( timestamp ) ) return new Date( timestamp );
Dai
  • 141,631
  • 28
  • 261
  • 374
  • Can you be more specific i need to compare the dates kess, greater, same dates in YYYY/MM/DD formate can U have any – Ganesh Sudarsan Dec 14 '15 at 08:02
  • @GaneshSudarsan You should be able to pass the string values directly to the `Date(string)` constructor and compare the instances. What problem are you having specifically? – Dai Dec 14 '15 at 08:04
  • Hi, on validating form I am giving inputs as from (2015/02/__) & To date (2015/02/__) in those input dates Iam giving Year, Month but not Date even though it is acception and submiting the form – Ganesh Sudarsan Dec 14 '15 at 11:23
0

You don't need regular expression. In fact, you don't even need to parse the date as suggested by @Dai. Dates in the ISO-8601 format can be compared as strings:

'2015-12-14' < '2015-12-15' // true
'2015-12-20' == '2015-12-20' // true

Alphabetical sorting of the strings will yield dates chronologically, because of the ordering, i.e. year first, then month, then day, and because of the leading 0 in single digit numbers, such that 04 < 10.

This, of course, implies that the strings are always valid ISO-8601 dates.

fphilipe
  • 9,739
  • 1
  • 40
  • 52