Skip to content

Commit

Permalink
Improve roundToNearestMonth example
Browse files Browse the repository at this point in the history
  • Loading branch information
mjomble authored and ptomato committed Jan 15, 2024
1 parent 8d9df7f commit 9d64b88
Showing 1 changed file with 8 additions and 7 deletions.
15 changes: 8 additions & 7 deletions docs/cookbook/roundToNearestMonth.mjs
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
const date = Temporal.PlainDate.from('2018-09-16');

let { year, month } = date;
if ((date.day - 1) / date.daysInMonth >= 0.5) month++;
if (month > 12) {
month %= 12;
year++;
}
const nearestMonth = Temporal.PlainDate.from({ year, month, day: 1 });
const firstOfCurrentMonth = date.with({ day: 1 });
const firstOfNextMonth = firstOfCurrentMonth.add({ months: 1 });

const sinceCurrent = date.since(firstOfCurrentMonth);
const untilNext = date.until(firstOfNextMonth);

const isCloserToNextMonth = Temporal.Duration.compare(sinceCurrent, untilNext) >= 0;
const nearestMonth = isCloserToNextMonth ? firstOfNextMonth : firstOfCurrentMonth;

assert.equal(nearestMonth.toString(), '2018-10-01');

0 comments on commit 9d64b88

Please sign in to comment.