首页 > 解决方案 > 打字稿中的日期验证

问题描述

我正在学习日期处理,我有一个带有开始和结束日期的对象。例如:开始日期 =“2019-12-05”和结束日期 =“2020-05-20”

我想要做的是创建一个条件来检查日期是否不为空,然后开始日期将与现有日期相同或不小于今天日期的新日期。

if ((startDate != null && endDate != null) && (????????????????)) {
    alert('Incorrect date');
     this.dateNotValid = false;
}

代替??????在代码中,我想要一个逻辑,强制 startdate 为“2019-12-05”或今天的日期“2020-03-02”及以上,任何其他日期都应标记警报错误。

标签: javascripttypescriptif-statement

解决方案


我不确定我理解你的意思a condition that checks if the dates are not empty, and then that the startdate would either be the same as the existing date or a new date that is not less than today's date.

但我会这样编辑代码:

let myInputDate = new Date('any-date-you-want')

let startDate = new Date('2019-12-05'); // sample date
let endDate = new Date('2020-05-20'); // sample date

if ((!!startDate && !!endDate) && ((myInputDate != startDate) && (myInputDate > endDate))) {
    alert('Incorrect date');
    this.dateNotValid = false;
}

正如@Abhishek 所说,考虑使用momentwhich 是一个有用的库来处理日期对象。


推荐阅读