【问题标题】:Javascript / Typescript: Compare Date, string, and Moment variablesJavascript / Typescript:比较日期、字符串和时刻变量
【发布时间】: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 环境,

资源:

Converting a string to a date in JavaScript

【问题讨论】:

    标签: javascript angular typescript momentjs angular10


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 2014-04-21
      • 2013-10-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-10-19
      • 1970-01-01
      • 2014-09-09
      • 1970-01-01
      相关资源
      最近更新 更多