Languages
[Edit]
EN

JavaScript - detecting invalid date

8 points
Created by:
Lily
548

In this article, we're going to have a look at how to check if data is invalid in JavaScript.

Date correctness can be checked basing on internal state of Date object.

Incorrect date object returns:

  • false for call isFinite(myDate),
  • true for call isNaN(myDate),
  • NaN from myDate.getTime() method,
  • "Invalid Date" string for toString() method call.

Quick solution:

 

Look below to see different practical examples:

1. Date object test example

Edit

This approach is based on fact: isFinite method returns false for incorrect dates.

2. getTime() or other getter test example

Edit

This approach is based on fact: incorrect date returns NaN values from getters. So we can make a simple test for example with getTime() method.

3. toString() method test example

Edit

This approach is based on fact: incorrect date object returns "Invalid Date" string for toString() method call. It is good to call to string method with protoype API that prevents methods overriding.

4. Detecting correct date string or date object example

Edit

The example presented in this section allows checking the correctness of the date provided as a string or object. String date should be formatted according to one of the standards:

  • IETF-compliant RFC 2822 timestamps,
  • ISO 8601.

Run the following code to see the effect:

Alternative titles

  1. JavaScript - how to check if date is invalid?
  2. JavaScript - how to check if date is correct?
  3. JavaScript - checking date correctness
  4. JavaScript - detecting incorrect date
1
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join