Check if string is a date value

What is an easy way to check if a value is a valid date, any known date format is allowed.

For example, I have values 10-11-2009 , 10/11/2009 , 2009-11-10T07:00:00+0000 , which should be recognized as date values, and values 200 , 10 , 350 that should not be recognized as the date value. What is the easiest way to test this if possible? Because timestamps will also be allowed.

+177
source share
24 answers

Is Date.parse() enough?

See its relative MDN documentation page .

+40
source

2015 update

This is an old question, but other new questions:

close as duplicates of this, so I think itโ€™s important to add fresh information here. I write this because I got scared thinking that people really copy and paste part of the code posted here and use it in production.

Most of the answers here either use some complex regular expressions that correspond only to some very specific formats, and actually do it wrong (for example, matching on January 32nd rather than matching the actual ISO date as advertised - see the Demo ) or they try to pass something to the Date constructor and wish them the best.

Using Moment

As I explained in this answer, the library is currently available for this: Moment.js

This is a library for analyzing, checking, processing and displaying dates in JavaScript, which has a much richer API than the standard JavaScript date processing functions.

This is 12kB minified / gzipped and works in Node.js and other places:

 bower install moment --save # bower npm install moment --save # npm Install-Package Moment.js # NuGet spm install moment --save # spm meteor add momentjs:moment # meteor 

Using Moment, you can be very specific about checking the correct dates. Sometimes itโ€™s very important to add some hints about the format you expect. For example, a date like 06/22/2015 looks like a valid date unless you use the DD / MM / YYYY format, in which case this date should be rejected as invalid. There are several ways you can tell Moment which format you expect, for example:

 moment("06/22/2015", "MM/DD/YYYY", true).isValid(); // true moment("06/22/2015", "DD/MM/YYYY", true).isValid(); // false 

true argument is that Moment will not try to parse the input unless it exactly matches one of the provided formats (in my opinion, this should be the default behavior).

You can use the internal format:

 moment("2015-06-22T13:17:21+0000", moment.ISO_8601, true).isValid(); // true 

And you can use several formats as an array:

 var formats = [ moment.ISO_8601, "MM/DD/YYYY :) HH*mm*ss" ]; moment("2015-06-22T13:17:21+0000", formats, true).isValid(); // true moment("06/22/2015 :) 13*17*21", formats, true).isValid(); // true moment("06/22/2015 :( 13*17*21", formats, true).isValid(); // false 

See DEMO .

Other libraries

If you do not want to use Moment.js, there are other libraries:

2016 update

I created an immoment module similar to (a subset of) Moment, but without surprises caused by mutations of existing objects (see the docs for more details).

2018 update

Today, I recommend using Luxon date / time processing instead Moment, which (unlike the Moment) makes the whole object intact, so no unpleasant surprises associated with the implicit mutation dates.

More information

See also:

Rob Gravel's JavaScript Parsing Series:

Bottom line

Of course, anyone can try to invent a wheel, write a regular expression (but please actually read ISO 8601 and RFC 3339 before doing this) or call buit in the random data constructors to parse the error messages like 'Invalid Date' (Are you saying this message is exactly the same on all platforms? In all locales? In the future?), Or you can use the proven solution and use your time to improve it, and not reinvent it. All of the libraries listed here are free open source software.

+218
source

This is how I solved this problem in the application I'm working on now:

updated based on reviews from krillgar:

 var isDate = function(date) { return (new Date(date) !== "Invalid Date") && !isNaN(new Date(date)); } 

or...

 var isDate = function(date) { return (new Date(date) !== "Invalid Date" && !isNaN(new Date(date)) ) ? true : false; } 

....

+59
source

new Date(date) === 'Invalid Date' only works in Firefox and Chrome. IE8 (the one I have on my machine for testing) gives NaN.

As said to the accepted answer, Date.parse(date) will also work for numbers. Therefore, to get around this, you can also check that it is not a number (if that is what you want to confirm).

 var parsedDate = Date.parse(date); // You want to check again for !isNaN(parsedDate) here because Dates can be converted // to numbers, but a failed Date parse will not. if (isNaN(date) && !isNaN(parsedDate)) { /* do your work */ } 
+22
source

How about this? It will check if it is a Date object or a date string:

 function isDate(value) { var dateFormat; if (toString.call(value) === '[object Date]') { return true; } if (typeof value.replace === 'function') { value.replace(/^\s+|\s+$/gm, ''); } dateFormat = /(^\d{1,4}[\.|\\/|-]\d{1,2}[\.|\\/|-]\d{1,4})(\s*(?:0?[1-9]:[0-5]|1(?=[012])\d:[0-5])\d\s*[ap]m)?$/; return dateFormat.test(value); } 

I should point out that this does not check ISO formatted strings, but with a bit of work with RegExp you should be good.

+7
source

None of the answers here checks if the date is invalid, for example, February 31. This function accesses this by checking if the returned month matches the original month and make sure that the actual year has been presented.

 //expected input dd/mm/yyyy or dd.mm.yyyy or dd-mm-yyyy function isValidDate(s) { var separators = ['\\.', '\\-', '\\/']; var bits = s.split(new RegExp(separators.join('|'), 'g')); var d = new Date(bits[2], bits[1] - 1, bits[0]); return d.getFullYear() == bits[2] && d.getMonth() + 1 == bits[1]; } 
+7
source

Use a regex to test it.

 isDate('2018-08-01T18:30:00.000Z'); isDate(_date){ const _regExp = new RegExp('^(-?(?:[1-9][0-9]*)?[0-9]{4})-(1[0-2]|0[1-9])-(3[01]|0[1-9]|[12][0-9])T(2[0-3]|[01][0-9]):([0-5][0-9]):([0-5][0-9])(.[0-9]+)?(Z)?$'); return _regExp.test(_date); } 
+4
source

I would do it

 var myDateStr= new Date("2015/5/2"); if( ! isNaN ( myDateStr.getMonth() )) { console.log("Valid date"); } else { console.log("Invalid date"); } 

Play here

+3
source

By sending all of the above comments, I came to a solution.

This works if the date has passed in ISO format or should be used for other formats.

 var isISO = "2018-08-01T18:30:00.000Z"; if(new Date(isISO) !== "Invalid Date" && !isNaN(new Date(isISO)) ) { if(isISO==new Date(isISO).toISOString()){ console.log("Valid date"); } else { console.log("Invalid date"); } } else { console.log("Invalid date"); }' 

you can play here on jsfiddle

+3
source

Here is a minimalist version.

 var isDate = function (date) { return!!(function(d){return(d!=='Invalid Date'&&!isNaN(d))})(new Date(date)); } 
+2
source

After reading all the answers listed above, I got the following:

 var checkDateValue = function(date) { return date && (!(new Date(date) == "Invalid Date") && !isNaN(new Date(date))); }; 

Note that new Date(date) !== "Invalid Date" always matters. Hope this helps.

+1
source

This function called works fine, returns true for a valid date. Be sure to call using the date in ISO format (yyyy-mm-dd or yyyy / mm / dd):

 function validateDate(isoDate) { if (isNaN(Date.parse(isoDate))) { return false; } else { if (isoDate != (new Date(isoDate)).toISOString().substr(0,10)) { return false; } } return true; } 
+1
source

Date can be confirmed using the following answer.

  var year=2019; var month=2; var date=31; var d = new Date(year, month - 1, date); if (d.getFullYear() != year || d.getMonth() != (month - 1) || d.getDate() != date) { alert("invalid date"); return false; } 
+1
source

I know this is an old question, but I ran into the same problem and saw that none of the answers worked properly - in particular, dropping numbers (1200, 345, etc.) from dates that is original question. Here is a pretty unorthodox method that I could think of, and it seems to work. Please indicate if there are any cases where it will fail.

 if(sDate.toString() == parseInt(sDate).toString()) return false; 

This is a line for clipping numbers. So the whole function might look like this:

 function isDate(sDate) { if(sDate.toString() == parseInt(sDate).toString()) return false; var tryDate = new Date(sDate); return (tryDate && tryDate.toString() != "NaN" && tryDate != "Invalid Date"); } console.log("100", isDate(100)); console.log("234", isDate("234")); console.log("hello", isDate("hello")); console.log("25 Feb 2018", isDate("25 Feb 2018")); console.log("2009-11-10T07:00:00+0000", isDate("2009-11-10T07:00:00+0000")); 
+1
source

Is it good to verify that a date-related function is available for an object to determine if it is a Date object or not?

like

 var l = new Date(); var isDate = (l.getDate !== undefined) ? true; false; 
0
source

This is how I do it. This does not apply to all formats. You must configure accordingly. I have control over the format, so it works for me

 function isValidDate(s) { var dt = ""; var bits = []; if (s && s.length >= 6) { if (s.indexOf("/") > -1) { bits = s.split("/"); } else if (s.indexOf("-") > -1) { bits = s.split("-"); } else if (s.indexOf(".") > -1) { bits = s.split("."); } try { dt = new Date(bits[2], bits[0] - 1, bits[1]); } catch (e) { return false; } return (dt.getMonth() + 1) === parseInt(bits[0]); } else { return false; } } 
0
source

Try it

 <input type="text" id="StartDay" value="2018/01/01" maxlength="10" /> $('#StartDay').change(function () { if ( ($('#StartDay').val().length == 10 && new Date($('#StartDay').val()) >= new Date("2018/01/01") && (new Date($('#StartDay').val()) !== "Invalid Date") && !isNaN(new Date($('#StartDay').val()))) == false) { ..... } }) 
0
source

To do this, I created a solution based on moment.js to detect ISO 8601, RFC 2822 and local formats, without the need to specify a parsing line (which I always do not want to enter in the "standard" format.) ...

https://github.com/patarapolw/valid-moment

0
source

Shortcut:

 if(!isNaN(Date.parse(date))) 
0
source

It works:

 var isDate = function(date) { return ((new Date(date)).toString() !== "Invalid Date") ? true : false; } 
-1
source

Ok, this is an old question, but I found another solution when checking the solutions here. For me, it works to check if the getTime () function is present in the date object:

 const checkDate = new Date(dateString); if (typeof checkDate.getTime !== 'function') { return; } 
-1
source

Below is a slightly more improved method that uses Date.parse() , but checks if the input is not a number:

 function isDate(s) { if(isNaN(s) && !isNaN(Date.parse(s)) return true; else return false; } 

Note: Date.parse () will parse numbers: for example, Date.parse(1) will return a date. So here we check if s number, whether it is a date.

-1
source
 SimpleDateFormat sdf = new SimpleDateFormat(dateFromat); sdf.setLenient(false); 

The default value is TRUE. Thus, even lines of the wrong format return good values.

I used it something like this:

 SimpleDateFormat formatter = new SimpleDateFormat("yyyy/MM/dd"); formatter.setLenient(false); String value = "1990/13/23"; try { Date date = formatter.parse(value); System.out.println(date); }catch (ParseException e) { System.out.println("its bad"); } 
-4
source

Try the following:

 if (var date = new Date(yourDateString)) { // if you get here then you have a valid date } 
-5
source

Source: https://habr.com/ru/post/989134/


All Articles