| name | date-threshold-arithmetic |
| description | Date comparisons at thresholds fail due to fractional days: |
| lastReviewed | 2026-04-30T00:00:00.000Z |
Date Threshold Arithmetic
The Problem
Date comparisons at thresholds fail due to fractional days:
const daysBetween = (Date.now() - someDate.getTime()) / (1000 * 60 * 60 * 24);
The Solution
Always Math.floor() before threshold comparison.
function daysSince(date) {
const ms = Date.now() - new Date(date).getTime();
return Math.floor(ms / (1000 * 60 * 60 * 24));
}
if (daysSince(lastCheck) > 7) {
}
Common Traps
| Code | Bug |
|---|
days > 7 | Triggers on 7.0001 |
days >= 7 | Doesn't trigger on 6.9999 |
days === 7 | Never true for fractional values |
Safe Patterns
const fullDays = Math.floor((now - then) / MS_PER_DAY);
if (fullDays > threshold) { ... }
if (fullDays >= threshold) { ... }
if (fullDays === threshold) { ... }
For Cron-Style Checks
const lastRun = new Date(stored.lastRunTime);
const hoursSince = (Date.now() - lastRun.getTime()) / (1000 * 60 * 60);
if (Math.floor(hoursSince) >= 24) {
runTask();
}
Verification
const exactlySevenDaysAgo = new Date(Date.now() - 7 * 24 * 60 * 60 * 1000);
console.log(daysSince(exactlySevenDaysAgo));
When to Apply
- Cache expiration checks
- "Last N days" filters
- Scheduled task triggers
- Any date-based threshold
Tags
quality dates javascript bugs