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]);
}
}
}
booking object from database
console result
In console result, the 3rd one is unexpected according to the if statement. Any suggestion would be appreciated.
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]);
}
}
}
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With