首页 > 解决方案 > 将字符串验证为 JavaScript 日期格式

问题描述

我在验证来自new Date()Object 的以下字符串时遇到问题。 "2020-10-06T14:23:43.964Z". 就我而言,我期望这种输入格式或new Date(). 我正在尝试写一些类似于

const isValidDate = (d: Date):boolean => {
 if (d instanceof Date || /* check if valid Date string here */) {
   return true
 }
 return false
}

标签: javascripttypescriptdatevalidation

解决方案


也许这可以帮助你。

Date.prototype.isValid = function () { 
  // If the date object is invalid it 
  // will return 'NaN' on getTime()  
  // and NaN is never equal to itself. 
     return this.getTime() === this.getTime(); 
};

推荐阅读