Your input time is in UTC.

'2024-10-23T20:45:52.317Z'

But the rest of your code is using local system time.

e.g.

endDate.setMonth(startDate.getMonth() + periodInMonths);

So if you input a time of 9:00pm (in UTC) in your timezone (which is presumably 1 behind UTC?), that will be 8:00pm in the system’t local time.

So, either set the initial start date in the local system time zone, or keep it as UTC, but set all the dates in the code in UTC as well.