0

I need a time differnce in my react componenet. I have used MobX for my state management.Some Part of the code:

  <Icon name='clock' /> Expiry Date :- {format(books.returnDate, 'eeee do MMMM')}
  <Icon name='hourglass start' />Remaining Time:- {timeDiff(books.returnDate)}

In the above code books.returnDate is bind successfully. Now I need the time difference between books.returnDate and current Date so I called a function timeDiff

const timeDiff = (t2: Date) => {

        const t1 = new Date();
        console.log(t1.getDay())

        var d2 = t2.getDay();
        var d1 = t1.getDay();

        return (d2 - d1) / (24 * 3600 * 1000);
    }

In timeDiff function the values of both dates are:-

enter image description here

but the difference is not calculated. I am getting an error:

[mobx] Encountered an uncaught exception that was thrown by a reaction or observer component, in: 'Reaction[observer(LibrarianManager)]' TypeError: t2.getDay is not a function

How Can I find this differece in days?

Biraz Dahal
  • 361
  • 1
  • 5
  • 20

3 Answers3

1

This is off the assumption that books.returnDate is coming from your backend, probably as a part of a JSON response. You probably just forgot to convert it from a string to a date, since JSON can't store an actual date object.

So when you do something like:

const { data } = await axios.get('/api/books');
setState({books: data.books});

you just need to do:

const { data } = await axios.get('/api/books');
setState({books: data.books.map((book) => {
    book.returnDate = new Date(book.returnDate);
})});

or you could just do:

const timeDiff = (t2: Date) => {
    if (!(t2 instanceof Date)) t2 = new Date(t2);
    const t1 = new Date();
    console.log(t1.getDay)

    var d2 = t2.getDay();
    var d1 = t1.getDay();

    return (d2 - d1) / (24 * 3600 * 1000);
}
dave
  • 62,300
  • 5
  • 72
  • 93
0

You are calling getDay wrongly. It should be console.log(t1.getDay())

Michael
  • 1,806
  • 2
  • 11
  • 20
0

It seems like you already using date-fns or some similar library. If so then you don't need to invent things by yourself, just use appropriate function from the library, for example:

import differenceInHours from 'date-fns/differenceInHours'

differenceInHours(dateLeft, dateRight)

More: https://date-fns.org/docs/differenceInHours

Please note that date-fns v2 expects Date or number as an input anyway, not string.

Danila
  • 15,606
  • 2
  • 35
  • 67