I seem to be having a similar problem to this thread, where my JS dates are 1 day off, but I'm struggling a little to use the answers for a solution.
My problem seems to be down to timezone differences, BST(+1) vs GMT
For example, the clocks go forward two days after the first (correct) example, and then the rest are off:
console.log(new Date('2022', '02', '24')); // 24 (2022-03-24T00:00:00.000Z)
console.log(new Date('2022', '09', '24')); // 23 (2022-10-23T23:00:00.000Z)
console.log(new Date('2022', '08', '24')); // 23 (2022-09-23T23:00:00.000Z)
From the docs and that thread: If I create a date using strings it'll be in UTC, which is an hour behind me currently. And so because I'm not providing a time it assumes 00:00, which is actually 23:00UTC the previous day, right?
So I should use getTimezoneOffset()
if I want to get a consistent date 7 days ago?:
const oneWeekAgo = new Date(
utcDate.getFullYear(),
utcDate.getMonth(),
utcDate.getDate() - 7
) + utcDate.getTimezoneOffset();
This seems to get the date right, but not the format.
I just wanted to double check my approach so far, because the answer in the other thread seems to give the reasoning as being west of or behind UTC, when I'm currently east or infront, and the two didn't seem compatible as answers
Given a date string of "March 7, 2014", [Date.]parse() assumes a local time zone, but given an ISO format such as "2014-03-07" it will assume a time zone of UTC.