So it's pretty straight forwards:
import startOfMonth from 'date-fns/start_of_month';
export const getFirstDayThisMonth = date => {
const firstDay = startOfMonth(date);
return firstDay;
};
given input (for example):
1987-02-02T00:00:00.000Z
it returns:
1987-01-31T23:00:00.000Z
The error is reproduced exactly when trying to produce the first date according to the method mentioned in this answer:
var date = new Date();
var firstDay = new Date(date.getFullYear(), date.getMonth(), 1);
The error comes when running jest-tests and can't be reproduced in the console where it works as expected:
const day1 = new Date('1987-02-02');
undefined
const day2 = new Date(day1.getFullYear(),day1.getMonth(),1)
undefined
day2
Sun Feb 01 1987 00:00:00 GMT+0100 (Central European Standard Time)
If in the second solution I also set the fourth argument (hour) to 1, it correctly handles:
1987-02-02T00:00:00.000Z
returning 1987-02-01T00:00:00.000Z
and
2001-03-03T00:00:00.000Z
returning 2001-03-01T00:00:00.000Z
but
2002-04-04T00:00:00.000Z
returns 2002-03-31T23:00:00.000Z
I'm really at loss as to what could be causing this issue, it feels like there's some rollover to the previous date when the time is set to 00:00:00?
Per request, here's the date-fns
-code for startOfMonth:
function startOfMonth (dirtyDate) {
var date = parse(dirtyDate)
date.setDate(1)
date.setHours(0, 0, 0, 0)
return date
}
I really don't get why
var date = new Date();
var firstDay = new Date(date.getFullYear(), date.getMonth(), 1, 1);
seem to work on feb-march but not on april?