dev3 ·
new Date('2025-03-10').getDate() returns 9 on my machine in New York, but new Date('2025-03-10 00:00') returns 10. Why, and how do I handle dates safely?
0
DEV3 Developer Forum
Every post is reviewed first. Usually reviewed within 24 hours.
new Date('2025-03-10').getDate() returns 9 on my machine in New York, but new Date('2025-03-10 00:00') returns 10. Why, and how do I handle dates safely?
The two strings are parsed differently.
'2025-03-10' (ISO date-only) is parsed as UTC midnight. In New York (UTC-4/-5) that is the previous evening, so local getters like getDate() return 9.'2025-03-10T00:00' or '2025-03-10 00:00' (date-time without offset) is parsed as local time. The space format is not guaranteed by the spec, though all major engines accept it.Be explicit:
new Date(2025, 2, 10); // local midnight (month is 0-based)
new Date('2025-03-10T00:00:00'); // local
new Date('2025-03-10T00:00:00Z'); // UTC
Read in the same frame you created:
d.getUTCDate(); // for UTC-created dates
d.toISOString(); // always UTC, e.g. 2025-03-10T00:00:00.000Z
new Intl.DateTimeFormat('en-GB', {
dateStyle: 'medium', timeStyle: 'short', timeZone: 'Asia/Kolkata',
}).format(date);
Use timeZone to display in a chosen zone rather than the browser's.
YYYY-MM-DD strings and do not convert them to Date unless needed.Adding days across a daylight-saving change with + 86400000 is wrong by an hour. Use setDate:
const d = new Date(start);
d.setDate(d.getDate() + 30);
Temporal is the modern replacement and is shipping in newer engines, but check browser support before relying on it; libraries such as date-fns, Luxon or Day.js are safe choices today.
Use the Unix timestamp converter to check epoch values quickly.