From cd93e7edd2030ced9f7cd0e7d7dc0f47c2ebac5b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Faruk=20Mollao=C4=9Flu?= Date: Thu, 8 Oct 2020 16:39:23 +0300 Subject: [PATCH] Added a snippet isDateValid (#1415) Co-authored-by: Isabelle Viktoria Maciohsek --- snippets/isDateValid.md | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) create mode 100644 snippets/isDateValid.md diff --git a/snippets/isDateValid.md b/snippets/isDateValid.md new file mode 100644 index 000000000..2ad17c3b1 --- /dev/null +++ b/snippets/isDateValid.md @@ -0,0 +1,23 @@ +--- +title: isDateValid +tags: date,intermediate +--- + +Returns `true` if a valid date object can be created from the given values, `false` otherwise. + +- Use the spread operator (`...`) to pass the array of arguments to the `Date` constructor. +- Use `Date.prototype.valueOf()` and `Number.isNaN()` to check if a valid `Date` object can be created from the given values. + +```js +const isDateValid = (...val) => !isNaN(new Date(...val).valueOf()); +``` + +```js +isDateValid('December 17, 1995 03:24:00'); // true +isDateValid('1995-12-17T03:24:00'); // true +isDateValid('1995-12-17 T03:24:00'); // false +isDateValid('Duck'); // false +isDateValid(1995, 11, 17); // true +isDateValid(1995, 11, 17, 'Duck'); // false +isDateValid({}); // false +```