I have a bunch of timestamp formatted like this
const dates = ['2021.6.01', '2021.6.11', '2021.9.02']
I wanted to write a util that can tell me if a date with such a format is within the last X days of another date.
For example, 2021.6.10 is within the last 7 days of 2021.6.12 while 2021.6.01 is not within the last 7 days of 2021.6.12.
I was think the API interface would be but please feel free to suggest a better naming
function isWithinTheLastDays(originalDate, date, days)
I found it really tricky to implement by hand and there are a lot of edge cases.
Parse the dates with the Date constructor, subtract the two dates and convert the millisecond difference to days (by dividing by 86400000), then check whether it is smaller or equal to days:
function isWithinTheLastDays(originalDate, date, days){
return (new Date(date) - new Date(originalDate)) / 86400000 <= days;
}
console.log(isWithinTheLastDays('2021.6.10', '2021.6.12', 7)) //2 day diff
console.log(isWithinTheLastDays('2021.6.10', '2021.6.17', 7)) //7 day diff
console.log(isWithinTheLastDays('2021.6.10', '2021.6.18', 7)) //8 day diff
You can try this:
Note: this will return true if the dates is X days after and before the date you've set
const dates = ['2021.08.26', '2021.6.11', '2021.9.02']
function isWithinDays({ originalDate, date, range }) {
return parseInt(((new Date(date) - new Date(originalDate)) / (1000 * 60 * 60 * 24)), 10) <= range && parseInt(((new Date(date) - new Date(originalDate)) / (1000 * 60 * 60 * 24)), 10) >= 0 ? true : false
}
for (var i = 0; i < dates.length; i++) {
console.log(isWithinDays({
originalDate: dates[i],
date: new Date('2021-08-27'),
range: 10
}))
}
turning it to Unix timestamp and subtracting it
function isWithinTheLastDays(originalDate, date, days){
if(Math.abs(
new Date(date).getTime()/1000
- new Date(originalDate).getTime()/1000
)/60/60/24 >= days){
return true;
}else{
return false;
};
}