Javascript / Typescript:比较日期、字符串和时刻变量

Javascript / Typescript: Compare Date, string, and Moment variables

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

无论出于何种原因,从 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 环境,

资源:

Converting a string to a date in JavaScript

您可以使用 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>