What is the best way to initialize a JavaScript Date to midnight?
Instantly set a JS Date
object to midnight with:
Result: Today's date at 00:00:00.000.
To set to midnight using UTC, use:
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:
Travelling in UTC
This method is universal, giving midnight in UTC:
Utilizing third-party libraries
If you're using Moment.js, setting dates to midnight becomes a kid's job:
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.
Was this article helpful?