【发布时间】:2020-08-02 00:15:10
【问题描述】:
我正在比较两个日期变量。
无论出于何种原因,从 C# API 到 Javascript,由于以前的公司代码,它们有时会转换为 1) string 或 2) Date 甚至 3) Moment。
Typescript 在下面的界面中声明它们是 Date,但在 Javascript 运行时,它会发生变化。
那么现在,在比较两个日期时,有没有一种简单的方法可以简化下面的代码?
将所有内容转换为日期,并进行getTime() 比较。
export interface Product {
productName?: string;
recordDate?: Date;
}
if (product1.recordDate instanceof Date) {
dateVar1 = product1.recordDate;
} else if (typeof product1.recordDate === 'string') || product1.recordDate instanceof String)) {
dateVar1 = new Date(product1.recordDate);
} else if (product1.recordDate instanceof moment) {
dateVar1 = ((product1.recordDate as any) as moment.Moment).toDate();
}
if (product2.recordDate instanceof Date) {
date2Var = product2.recordDate;
} else if (typeof product2.recordDate === 'string') || product2.recordDate instanceof String)) {
date2Var = new Date(product2.recordDate);
} else if (product2.recordDate instanceof moment) {
date2Var = ((product2.recordDate as any) as moment.Moment).toDate();
}
if date1Var.getTime() === date2Var.getTime() {
return true;
} else {
return false;
}
使用 Angular 环境,
资源:
【问题讨论】:
标签: javascript angular typescript momentjs angular10