-
I want to be able to do isAfter() but like moment's I realize I can use startOfDay/Month/etc on each... I'm just curious if there was a way to have this happen automatically. I may just be missing it in the docs, and it's already possible... any suggestions for something better? |
Beta Was this translation helpful? Give feedback.
Replies: 3 comments 3 replies
-
The For your use case, have you tried the import { differenceInMonths } from "date-fns";
const earlier = new Date(2020, 0, 1);
const later = new Date(2021, 4, 3);
console.log(differenceInMonths(earlier, later)); // -16
console.log(differenceInMonths(later, earlier)); // 16
console.log(differenceInMonths(later, earlier) > 0); // true |
Beta Was this translation helpful? Give feedback.
-
I'm playing with this right now and it seems to be doing the job. I'm doing more testing... export function isSameOrAfter(target, type, origin = new Date()) {
switch (type) {
case 'year':
return startOfYear(target) >= startOfYear(origin)
case 'month':
return startOfMonth(target) >= startOfMonth(origin)
case 'day':
return startOfDay(target) >= startOfDay(origin)
case 'hour':
return startOfHour(target) >= startOfHour(origin)
case 'minute':
return startOfMinute(target) >= startOfMinute(origin)
default:
throw new Error(`isSameOrAfter - unrecognized precision type: ${type}!`)
}
} |
Beta Was this translation helpful? Give feedback.
-
@srevenant It's a slow day, so here's an alternate approach for you with benchmarks. It seems to perform better for most paths and equal at worst. import {
isSameDay,
isSameHour,
isSameMinute,
isSameMonth,
isSameYear,
} from 'date-fns'
export function isSameOrAfter(target, type, origin = new Date()) {
if (target.getTime() >= origin.getTime()) return true
switch (type) {
case 'year':
return isSameYear(origin, target)
case 'month':
return isSameMonth(origin, target)
case 'day':
return isSameDay(origin, target)
case 'hour':
return isSameHour(origin, target)
case 'minute':
return isSameMinute(origin, target)
default:
throw new Error(`isSameOrAfter - unrecognized precision type: ${type}!`)
}
} All later dates bench at For earlier dates:
|
Beta Was this translation helpful? Give feedback.
I'm playing with this right now and it seems to be doing the job. I'm doing more testing...