繁体   English   中英

打字稿中的日期验证

[英]Date validations in typescript

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

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

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

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

我不确定我是否理解您所说的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.意思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 所说,考虑使用moment ,这是一个有用的库来处理日期对象。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM