0

I have an ion-card that displays information read from firebase. 1 such piece of information is a date. If the date is equal to today then I want to do some styling.

In my html ion-card-content tag I have the following code

<ion-card-content [ngClass]="isMatchDateToday(match?.date.seconds * 1000)">

I want to call a function that passes in the date as a parameter and compares it today's date.

   isMatchDateToday(date: Date){



    }

I'm really not sure how to compare the dates. I've used today = date.now() and tried to compare it with my date however when console.log the values they have a long numerical values of different length.

I'd expect something like this (pesudocode)

isMatchDateToday(date: Date){
        var today = Date.now();
        if (date == today)
            {
            return "css-class-name";
            }
        }
  • yson's answer will work, but here are some more options: https://stackoverflow.com/a/43855221, https://stackoverflow.com/a/31764918, and probably more from here: https://www.google.com/search?q=javascript+check+if+two+date+objects+are+on+the+same+day – Frank van Puffelen Sep 12 '19 at 16:45
  • My problem on @yson 's answer is that I get the console error 'value.toISOString is not a function' – Barry the Beginner Sep 13 '19 at 16:06

1 Answers1

2

example - (discarding hours, minutes, seconds)

// sample method to generate the Date object
const firetimestamp =  new Date(firebasetimestamp.seconds * 1000);
// sample dates
const entry1 = new Date('2019-09-12'); 
const entry2 = new Date('2019-09-13');

you can choose to use Date.prototype.toISOString(). https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toISOString

export function Compare(value: Date): string {
  const today: Date = new Date();
  if (today.toISOString().substr(0, 10) === value.toISOString().substr(0, 10)) {
    return "success class-name";
  } else {
    return "error class-name";
  }
}

console.log(Compare(entry1));
console.log(Compare(entry2));

Note: take today's date from the client not from the server

yson
  • 276
  • 1
  • 6
  • My problem is that when I do value.toISOString() I get the console error 'value.toISOString is not a function' @yson – Barry the Beginner Sep 13 '19 at 14:47
  • Interesting. The page that yson linked shows that this should work in most modern environments. Where are you running this? – Frank van Puffelen Sep 13 '19 at 18:39
  • Remember that toISOString () is a method of the javascript date object. not of the firebase timestamp object. in its function, it indicates that the parameter it receives is a type of date (therefore, another type of object must become a type of date). You are using firestore, real-time database or cloud functions. – yson Sep 15 '19 at 13:03