Reputation: 135
I am trying to compare dated in typescript/angular 4. In my case, I assigned system date into a variable named 'today' and database date assigned into a variable named 'dateToBeCheckOut'. Then I compared dates using if statement, In my case I expected to get the bookings which having checkout date is less than(before) today's date. But I get unexpected result instead of getting the expected result. I attached my code bellow and expect someone's help for understanding why it happens.
Here is the code
for(let k = 0; k < this.bookingDetailsArrayRealObject.length; k++){
let dateCheckOut = this.bookingDetailsArrayRealObject[k].package.chackout;
let dateToBeCheckOut = new Date(dateCheckOut);
let today = new Date(Date.parse(Date()));
//let today_test = new Date();
if(this.bookingDetailsArrayRealObject[k].status){
if(dateToBeCheckOut.toDateString() < today.toDateString()){
this.bookingIdsToBeUpdated.push(this.bookingDetailsArrayRealObject[k]._id);
window.alert('true');
console.log(today.toDateString());
console.log(dateToBeCheckOut.toDateString());
console.log(this.bookingDetailsArrayRealObject[k]);
}
}
}
In console result, the 3rd one is unexpected according to the if statement. Any suggestion would be appreciated.
Upvotes: 6
Views: 33763
Reputation: 1847
Just a guess, did you check the timezone of the date objects at runtime?
When i had to handle local (browser) date/time and database (server) date/times i very often had the problem of different timezones.
An example: The database sends a date (in UTC), in the format "20190621T00:00:00" (ISO-8601 conform but without timezone information) I transfered that information with Date("20190621T00:00:00") into a Date object.
Now the fun started, because my computer was NOT in the UTC Timezone but in +02:00. And "Date()" assumes the current timezone, if no timezone is delivered.
As a result, my Date-Object then represented the date/time "20190621T00:00:00+02:00". And that´s a bit different then "20190621T00:00:00+00:00" what may database wanted to give me.
So i had database log entries that came directly from the future :-)
Perhaps
let databaseDate = new Date(Date.UTC(sourceDate));
let localDate = new Date(Date.UTC());
could help you?
Warm regards
Upvotes: 1
Reputation: 7165
You can compare date objects without casting them as strings. Try:
for(let k = 0; k < this.bookingDetailsArrayRealObject.length; k++){
let dateCheckOut = this.bookingDetailsArrayRealObject[k].package.chackout;
let dateToBeCheckOut = new Date(dateCheckOut);
let today = new Date();
//let today_test = new Date();
if(this.bookingDetailsArrayRealObject[k].status){
if(dateToBeCheckOut < today){
this.bookingIdsToBeUpdated.push(this.bookingDetailsArrayRealObject[k]._id);
window.alert('true');
console.log(today.toDateString());
console.log(dateToBeCheckOut.toDateString());
console.log(this.bookingDetailsArrayRealObject[k]);
}
}
}
Upvotes: 5