Replies: 2 comments
-
I don't think there's a function in the library that can do this. You could use import { intervalToDuration } from "date-fns";
function formatDistanceInMonths(interval) {
const dur = intervalToDuration(interval);
let months = dur.years * 12 + dur.months;
// also treat 30+ days as a month
months += Math.floor(dur.days / 30);
if (months >= 1) {
const plural = months > 1 ? "s" : "";
return months + " month" + plural;
} else {
return "less than a month";
}
}
const now = new Date(2021, 10, 1);
console.log(formatDistanceInMonths({ start: new Date(2020, 2, 4), end: now })); // 19 months
console.log(formatDistanceInMonths({ start: new Date(2021, 9, 1), end: now })); // 1 month
console.log(formatDistanceInMonths({ start: new Date(2021, 2, 2), end: now })); // 8 months
console.log(formatDistanceInMonths({ start: new Date(2021, 10, 1, 10), end: now })); // less than a month |
Beta Was this translation helpful? Give feedback.
0 replies
-
All good, thanks. This actually worked for my use case. Contracts will be about a year max so I just needed to account for 1 month & 1 year. A simple if/else took care of it.
|
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
Hey!
How do I convert
30 days
to1 month
and1 year
to12 months
?As in, I want everything in months.
Beta Was this translation helpful? Give feedback.
All reactions