我想写一个条件,某人选择的航班日期等于/大于今天:
服务如下:
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root',
})
export class FlightSelectionService {
startingCity: string = 'Warsaw';
selectedEndingCity: string = 'Paris';
startingDate: Date = new Date();
endingDate: Date = this.startingDate;
currentDate: Date = new Date();
adultsNumber: number = 0;
childrenNumber: number = 0;
validatePassengers(): boolean {
const totalPassengers = this.adultsNumber + this.childrenNumber;
return totalPassengers > 0;
}
validateDates(): boolean {
console.log(this.startingDate + ' ' + this.startingDate.getTime());
console.log(this.currentDate + ' ' + this.currentDate.getTime());
console.log(this.startingDate.getTime() === this.currentDate.getTime());
const isStartingDateValid =
this.startingDate.getTime() >= this.currentDate.getTime();
const isEndingDateValid = this.endingDate > this.startingDate;
const areDatesDifferent =
this.startingDate.getTime() !== this.endingDate.getTime();
return isStartingDateValid && isEndingDateValid && areDatesDifferent;
}
constructor() {}
}
以及 valide Date 函数中的验证代码:
console.log(this.startingDate + ' ' + this.startingDate.getTime());
console.log(this.currentDate + ' ' + this.currentDate.getTime());
console.log(this.startingDate.getTime() === this.currentDate.getTime());
const isStartingDateValid =
this.startingDate.getTime() >= this.currentDate.getTime();
它不起作用,我尝试过:
const startingDateInUTC = new Date(this.startingDate.getUTCFullYear(), this.startingDate.getUTCMonth(), this.startingDate.getUTCDate());
const currentDateInUTC = new Date(this.currentDate.getUTCFullYear(), this.currentDate.getUTCMonth(), this.currentDate.getUTCDate());
const isStartingDateValid = startingDateInUTC.getTime() >= currentDateInUTC.getTime();
如何正确实现这个日期比较?起始日期必须是当前日期或更高,因此我可以预订当天或未来的航班,而不是过去的航班。
编辑:
console.log(this.startingDate + ' ' + this.startingDate.getTime());
console.log(this.currentDate + ' ' + this.currentDate.getTime());
是:
Wed Apr 17 2024 12:57:12 GMT+0200 (Central European Summer Time) 1713351432419 flight-selection.service.ts:20:12
Wed Apr 17 2024 12:57:12 GMT+0200 (Central European Summer Time) 1713351432419
对于与日期相关的功能,moment.js 非常棒。您可以使用 isSameOrAfter。请阅读文档这里