Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to validate if a string is a valid date in js [duplicate]

I have string field which is used to get different values. Some of the values received are dates. Now I need to check if value received is date or not? The date received can be in different formats again.

I tried Date.parse(), it works if format is dd-mm-yyyy hh:mm, but I have some dates received in like (26/05/2015 06:20:57 +00:00).

How do I compare if string is valid date or not?

like image 954
DS2020 Avatar asked Jun 15 '15 13:06

DS2020


People also ask

How do you check if a date is a valid date in JavaScript?

Store the date object in a variable. If the date is valid then the getTime() will always be equal to itself. If the date is Invalid then the getTime() will return NaN which is not equal to itself. The isValid() function is used to check the getTime() method is equal to itself or not.

How do you validate if a string is a date?

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

How do you know if a date is valid?

Given date in format date, month and year in integer. The task is to find whether the date is possible on not. Valid date should range from 1/1/1800 – 31/12/9999 the dates beyond these are invalid. These dates would not only contains range of year but also all the constraints related to a calendar date.

Is valid date string JS?

One way to check if a string is date string with JavaScript is to use the Date. parse method. Date. parse returns a timestamp in milliseconds if the string is a valid date.


1 Answers

If Date.parse() is not enough for you - but it may be enough - see the documentation at:

  • https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/parse

then you may try:

  • Moment.js

It is a library to parse, validate, manipulate, and display dates in JavaScript, that has a much richer API than the standard JavaScript date handling functions.

See also this answer for more libraries and links to tutorials.

like image 113
rsp Avatar answered Oct 22 '22 00:10

rsp