date-fns icon indicating copy to clipboard operation
date-fns copied to clipboard

startOfMonth returning wrong date when input is first day of the month

Open AdamMarciniak opened this issue 2 years ago • 1 comments

When I run this:

console.log(new Date('2021-01-01'))
console.log('START', startOfMonth(new Date('2021-01-01')))

I get:

2021-01-01T00:00:00.000Z
START 2020-12-01T08:00:00.000Z

The startOfMonth function goes backwards to the previous month.

If I specify the 2nd of the month it works how it should.

AdamMarciniak avatar Apr 10 '24 16:04 AdamMarciniak

@AdamMarciniak

I couldn't reproduce this issue in my environment, but I believe it is similar to the problem described in issue #3764. It seems that the date gets processed as a local timezone within date-fns, which could be causing the discrepancy.

As mentioned in #3764, using UTCDate should prevent this issue: UTCDate companion package

import { startOfMonth } from "date-fns";
import { UTCDate } from "@date-fns/utc";

console.log(new UTCDate("2021-01-01"));
console.log("START", startOfMonth(new UTCDate("2021-01-01")));
console.log("START", startOfMonth(new UTCDate(2021, 0, 1)));

By using UTCDate, you should be able to get consistent results as expected.

sumodmatto avatar Apr 18 '24 03:04 sumodmatto