Explain Codes LogoExplain Codes Logo

What is the best way to initialize a JavaScript Date to midnight?

javascript
date-manipulation
javascript-best-practices
performance-optimization
Nikita BarsukovbyNikita Barsukov·Jan 20, 2025
TLDR

Instantly set a JS Date object to midnight with:

let midnight = new Date(); midnight.setHours(0,0,0,0);

Result: Today's date at 00:00:00.000.

To set to midnight using UTC, use:

let utcMidnight = new Date(); utcMidnight.setUTCHours(0,0,0,0);

Result: A new Date object set to midnight UTC.

Deciding between local and UTC time

In local land

This method gives you midnight in the local time zone:

let now = new Date(); now.setHours(0,0,0,0); // "I want to sleep at home tonight!"

Travelling in UTC

This method is universal, giving midnight in UTC:

let now = new Date(); now.setUTCHours(0,0,0,0); // "I'm a time traveler, local times are so passé."

Utilizing third-party libraries

If you're using Moment.js, setting dates to midnight becomes a kid's job:

let midnight = moment().startOf('day'); // "Look, ma! No hours!"

Remember: Moment.js offers cross-browser compatibility and more, but increases your payload.

Avoiding gotchas

Browser oddities

Browsers are like people, they have quirks. Code might run differently in each, so always test across environments.

Watch out for daylight savings

Don't forget, daylight saving time could steal an hour from your day, or give you an extra! Keep this head-scratcher in mind when manipulating hours.

Performance checks

Setting dates excessively could make your code run slower than a snail on holiday. Be wary of using these methods in hot code paths.

Writing optimised code

Be precise and concise

Keep code clear and maintainable by avoiding redundancy, ensuring your date and time code reads like a clock.

Code that tells a story

Self-explanatory code makes comments redundant and improves maintainability considerably.

One algorithm to rule them all

Design your date functions to be future-proof. This might mean not hardcoding values, and accommodating possible changes.