1

我正在比较两个日期变量。

无论出于何种原因,从 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 中将字符串转换为日期

4

1 回答 1

0

您可以使用Moment. 只需传递stringDateMoment值:

dateVar1 = moment(product1.recordDate).toDate();

工作示例

const stringDate = "2020-08-01";  // string
const dateDate = new Date();      // Date
const momentDate = moment();      // Moment

console.log(moment(stringDate).toDate());
console.log(moment(dateDate).toDate());
console.log(moment(momentDate).toDate());
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.27.0/moment.min.js"></script>

于 2020-08-02T02:08:18.603 回答