如何使用 angular 8 检查所选时间小于当前时间或大于当前时间

How to check selected time is less than current or greater than current time using angular 8

我正在处理约会项目,因为我想用当前时间检查约会时间 this.appointmentFromTime <= this.timeNow && this.appointmentToTime >= this.timeNow 但在这种情况下,时间会变成字符串,因此代码无法按预期工作 this.timeNow = formatDate(this.today, 'h:mm a', 'en-US', '');

处理日期字符串的最佳方法是将它们转换为 Date 对象。然后,您可以通过 date.getTime() > date2.getTime()

轻松 运行 进行比较

const dateString = '2020-09-24T16:57:23.985Z';

console.log('current time is greater', new Date().getTime() > new Date(dateString).getTime());

以上方法效果很好,但我们可以使用它来简化操作

let currentDateTime = new Date();
this.officeStartTime = new Date();
this.officeStartTime.setHours(7, 0, 0); // 7.00 am
this.officeEndTime = new Date();
this.officeEndTime.setHours(19, 0, 0); // 7.00 pm
if (this.officeStartTime <= currentDateTime && this.officeEndTime >= currentDateTime) {
  const source = interval(3600000); // one hour in milliseconds
  const text = 'Status Update';
  this.subscription = source.subscribe(val => this.refreshStatus(text));
}

我们还可以使用新日期转换任何日期和时间格式并检查条件 const dateString = '2020-09-24T16:57:23.985Z'; const dateStr = new Date(dateString); const currentDateTime = new Date(); console.log('current time is greater', dateStr > currentDateTime);