30秒学会 JavaScript 片段 · 2024年1月5日

30秒学会 JavaScript 片段 – Check if date is valid

Checks if a valid date object can be created from the given values.

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

代码实现

const isDateValid = (...val) => !Number.isNaN(new Date(...val).valueOf());

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

翻译自:https://www.30secondsofcode.org/js/s/is-date-valid