date-fns
date-fns copied to clipboard
startOfMonth returning wrong date when input is first day of the month
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
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.