Reputation: 1973
I am trying to compare 2 dates in angular.
My component looks like this:
@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());
});
}
and my service (only the relevant method for this qustion):
getHolidays(): Observable<Holiday[]> {
return this.http.get(this._employeeUrl + '/holidays')
.map(response => response)
.catch(this.handleError);
}
What I get in my console is:
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
When I tried to debug it, I've found out that the Date that comes from my db (mongoDB) it is actually in JSON format, so in my app appears to be string.
So, I cannot compare a string with a date. As you can see now in my console, the dates seem to be identic, but not the time, so even if I want to see if 8 August 2016 === 8 August 2018, because time's values it will always be false.
What do I have to do to solve this?
Upvotes: 0
Views: 612
Reputation:
Your dates have an ISO format.
Simply create new dates from it with
const start = new Date('your string of an ISO date');
Then convert it to timestamps
const startTS = start.getTime();
And it becomes a very simple number comparison.
Upvotes: 3