I am making a site that gets data from a speedrun.com API and puts the newest runs on the site in order of time. I recently added a feature where runs from the same day that the site is viewed will have a special icon showing that they are "NEW". This is my current solution (Javascript):
runs[i].date = "2021-12-12"; // The API does not return hours
if (new Date(new Date().getTime() - new Date().getTimezoneOffset() * 60000).toJSON().slice(0, 10) === runs[i].date) {
alert("Today");
}
If the date was December 12th, 2021, this would alert Today
.
This solution accounts for timezone differences and works well. However, I would like this to be possible for runs that happened in the last 3 days, so even if runs[i].date = "2021-10-12"
(December 10th) or runs[i].date = "2021-11-12"
(December 11th), it would still alert Today
.
How would this be done?
CodePudding user response:
Split it up into functions and compose them:
const DAY = 1000 * 60 * 60 * 24;
function datesAreInRange (date1, date2, days) {
const ms = days * DAY;
const diff = Math.abs(date2.getTime() - date1.getTime());
return diff <= ms;
}
function getDateFromString (ymd) {
const [y, m, d] = ymd.split('-').map(str => parseInt(str, 10));
return new Date(y, m - 1, d);
}
const today = '2021-12-16';
const otherDates = [
'2021-12-20',
'2021-12-19',
'2021-12-18',
'2021-12-17',
'2021-12-16',
'2021-12-15',
'2021-12-14',
'2021-12-13',
'2021-12-12',
];
for (const other of otherDates) {
const inRange = datesAreInRange(...[today, other].map(getDateFromString), 3);
console.log(`${other} is ${inRange ? '' : 'not '}in range.`)
}