To check if a date is yesterday:Subtract 1 day from the current date to get yesterday's date.
To check if two dates are the same day, call the toDateString() method on both Date() objects and compare the results. If the output from calling the method is the same, the dates are the same day.
Created Example For One hour Refer This and Then Change it to 24 Hours
const OneHourAgo= (date) => {
const hour= 1000 * 60 * 60;
const hourago= Date.now() - hour;
return date > hourago;
}
Simple One:-
var OneDay = new Date().getTime() + (1 * 24 * 60 * 60 * 1000)
day hour min sec msec
if (OneDay > yourDate) {
// The yourDate time is less than 1 days from now
}
else if (OneDay < yourDate) {
// The yourDate time is more than 1 days from now
}
Add this const oneday = 60 * 60 * 24 * 1000 (milliseconds)
. Since, JS converts difference between 2 Datetime objects into milliseconds. I think that should work
Using moment will be much easier in this case, You could try this:
let hours = moment().diff(moment(yourDateString), 'hours');
let days = moment().diff(moment(yourDateString), 'days');
It will give you integer value like 1,2,5,0etc so you can easily use condition check like:
if(hours >= 24) { your code }
or
if(days >= 1) { your code }
Also, one more thing is you can get more accurate result of the time difference (in decimals like 1.2,1.5,0.7etc) to get this kind of result we need to pass 3rd argument which i.e. true for precise result use this syntax:
let hours = moment().diff(moment(yourDateString), 'hours', true);
Let me know if you have any further query
Maybe something like that?
const now = Date.now();
// if it's a firebase timestamp
const createdAt = doc.data().created_at.toMillis();
const oneDay = 24 * 60 * 60 * 1000;
const isMoreThanADay = (now - createdAt) > oneDay;
I don't know firebase timestamps I relied on the documentation for the toMillis
method.
If you want to check any date from DB (in mysql format or any other) is not older then last 24 hours (in case of expire reset password link) you can use the following logic where in my case user.passwordTokenTimestamp
is value save in DB
let now = +new Date();
let createdAt = +new Date(Date.parse(user.passwordTokenTimestamp.toString()));
var oneDay = 24 * 60 * 60 * 1000;
if ((now - createdAt) > oneDay) {
const errors = {
User: 'Password reset token has expired, please resend forgot password email !',
};
throw new HttpException({ errors }, HttpStatus.UNPROCESSABLE_ENTITY);
}
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