首页 > 解决方案 > 如何将当前系统日期与另一个日期进行比较

问题描述

我从 API 获取字符串格式的日期。 End Date 2014-06-03T06:16:52. 我需要编写一个 if-else 逻辑并比较结束日期​​和当前日期。如果结束日期小于当前日期,则将客户显示为处于活动状态,如果结束日期大于将客户显示为活动。我已经尝试遵循逻辑,但我无法理解并从字符串中获取今天的时间。

  this.endDate = this.sampleData != null ? 
  this.sampleData.customerStartDate : null;
  this.currentDate = new Date();
  var dd = this.currentDate.getDate();
  var mm = this.currentDate.getMonth() + 1;
  var yyyy = this.currentDate.getFullYear();
  this.currentDate = new Date().toLocaleString()
  console.log('End Date', this.endDate);
  console.log('Current Date: ', this.currentDate);
  if (this.endDate == null) {
    this.customerStatus = 'Active';
  } else {
    this.customerStatus = 'In Active';
  }

我正在获取当前日期,因为Current Date: 4/2/2019, 1:23:34 AM 我希望能够获得与结束日期相同的格式。我的主要任务是比较日期如何实现?

标签: javascripthtmlangulartypescript

解决方案


理想情况下,您希望清理从 API 获取的日期,并将其转换为 JSDate对象。您可以通过仅保留2014-06-03T06:16:52部分并将其提供给new Date()构造函数来做到这一点。

new Date()您可以通过不带参数调用来获取当前日期。

您可以通过调用getTime()每个日期将日期转换为数字。

然后,您可以比较这些数字。

const incoming_date = new Date('2014-06-03T06:16:52');
const current_date = new Date();
if (incoming_date.getTime() < current_date.getTime() {
    // incoming_date is before current_date
} else {
    // current_date is before incoming_date
}

推荐阅读