我正在尝试比较两个日期。
我的组件如下所示:
@Input() holidays: Holiday[];
beforeMonthViewRender({ body }: { body: CalendarMonthViewDay[] }): void {
let plannedHoliday: Holiday[];
body.forEach(day => {
plannedHoliday = this.holidays.filter(x => {
const h = new Date(x.date),
d = typeof day.date;
console.log('Render ' + new Date(x.date) + ' ' + day.date + ' ' +
(new Date(h.getFullYear(), h.getMonth(), h.getDate()) === new Date(day.date.getFullYear(), day.date.getMonth(), day.date.getDate()));
return new Date(h.getFullYear(), h.getMonth(), h.getDate()) === new Date(day.date.getFullYear(), day.date.getMonth(), day.date.getDate());
});
}
和我的服务(仅此问题的相关方法):
getHolidays(): Observable<Holiday[]> {
return this.http.get(this._employeeUrl + '/holidays')
.map(response => response)
.catch(this.handleError);
}
我在控制台中得到的是:
Render Thu Mar 16 2017 02:00:00 GMT+0200 (Eastern European Standard Time) Mon Aug 08 2016 00:00:00 GMT+0300 (Eastern European Summer Time) false Render Tue Aug 09 2016 07:28:20 GMT+0300 (Eastern European Summer Time) Tue Aug 09 2016 00:00:00 GMT+0300 (Eastern European Summer Time) false Render Tue Aug 09 2016 03:00:00 GMT+0300 (Eastern European Summer Time) Tue Aug 09 2016 00:00:00 GMT+0300 (Eastern European Summer Time) false Render Wed Aug 10 2016 03:00:00 GMT+0300 (Eastern European Summer Time) Tue Aug 09 2016 00:00:00 GMT+0300 (Eastern European Summer Time) false Render Thu Aug 11 2016 03:00:00 GMT+0300 (Eastern European Summer Time) Tue Aug 09 2016 00:00:00 GMT+0300 (Eastern European Summer Time) false Render Fri Aug 12 2016 03:00:00 GMT+0300 (Eastern European Summer Time) Tue Aug 09 2016 00:00:00 GMT+0300 (Eastern European Summer Time) false
当我尝试调试它时,我发现来自数据库(mongoDB)的Date实际上是JSON格式的,因此在我的应用中似乎是字符串。
因此,我无法将字符串与日期进行比较。 正如您现在在控制台中看到的那样,日期似乎是相同的,但不是时间,所以即使我想看看是否2016年8月8日=== 2018年8月8日,因为时间的值始终是错误的。>
我该怎么办才能解决这个问题?
答案 0 :(得分:2)
您的日期具有ISO格式。
使用
可以从中轻松创建新日期const start = new Date('your string of an ISO date');
然后将其转换为时间戳
const startTS = start.getTime();
这变成了一个非常简单的数字比较。