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 ?
-
2What is the question? – Daniel B Dec 14 '15 at 07:41
-
Do you need a pattern to check if the string needed is a date? – anindis Dec 14 '15 at 07:41
-
2possible duplicate http://stackoverflow.com/questions/8937408/regular-expression-for-date-format-dd-mm-yyyy-in-javascript – Shailendra Sharma Dec 14 '15 at 07:42
-
Need the Regular expression to check the date formate in YYYY/MM/DD – Ganesh Sudarsan Dec 14 '15 at 07:42
2 Answers
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 );

- 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
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.

- 9,739
- 1
- 40
- 52