I am trying to work with time frames, using Date objects and changing parts of them, e.g., month, date. I have encountered inconsistencies in the representation of the Date objects as follows:
// create a new Date object using the current timestamp
let now = new Date();
// display the ISO representation (correct)
console.log(now.toISOString());
// display the date components (correct)
console.log(now.getFullYear() + "-" + (now.getMonth() + 1) + "-" + now.getDate());
// get the first day of the current month
var currentMonthFirstDate = new Date(now.getFullYear(), now.getMonth(), 1);
// display the ISO representation (wrong date)
console.log(currentMonthFirstDate.toISOString());
// display the date components (correct)
console.log(currentMonthFirstDate.getFullYear() + "-" + (currentMonthFirstDate.getMonth() + 1) + "-" + currentMonthFirstDate.getDate());
The sample output looks like this:
2023-04-24T08:43:27.819Z
2023-4-24
2023-03-31T21:00:00.000Z
2023-4-1
I could understand that it’s about time zones (even though I’m creating a new date with an explicit month and date given), but it still seems like an inconsistent behavior between the ISO string and the actual date components.
Is there something else I’m missing, or should there be another way of working with Date objects to create time frames? Is it actually correct, and I shouldn’t worry about it?