How to get start and end of day in Javascript?
Here's how to get sun-up and lights-out for 'today':
These yield sunUp
as the day's starting note and lightsOut
as the day's swansong.
Diving Deep with Time Zones
With the basics covered, let's go deeper. You can account for time zones in determining the start and end of a day. We did this by setting the local hours. To handle UTC or Coordinated Universal Time, tweak as follows:
To get the UTC string representation, call dawnUTC.toUTCString()
and duskUTC.toUTCString()
.
Having Ease with Libraries
If you're seeking simplicity, certain libraries can ease your labor with time zones and date formatting:
dayjs
providesdayjs.utc().startOf('day')
anddayjs.utc().endOf('day')
, effortlessly offering UTC times.Luxon's DateTime
markedly offers.local().startOf('day').toUTC().toISO()
and.local().endOf('day').toUTC().toISO()
, yielding ISO strings.
Bear in mind, only bring in a library if it truly enhances readability and simplifies your code architecture.
Beware of Potential Traps
Coding is an adventure. Watch your step for the occasional pitfall and gotcha:
- Daylight Saving Time. It can cause unexpected shifts when calculating start and end times.
- Leap seconds. They're rare but can trip you up, hence the end of day is at
23:59:59.999
, a fraction before the next day begins. - User interactions. If your responses depend on time validations, double-check your inputs.
Dealing with Formatting Needs
When you must wrestle with date-formatting, these tools are at your disposal:
- If you need ISO strings, employ
new Date().toISOString()
. - To convert local times into UTC just for display purposes, split on 'GMT' and append 'UTC':
new Date().toString().split('GMT')[0] + ' UTC'
. - Always cross-verify your outputs and formatting. In code debugging and particularly in formatting, console logs are the friend you never knew you needed.
Toolkit Selection Advice
Don't reach out for external libraries impulsively. The built-in JavaScript Date
may suffice. But if venturing into complex manipulations:
- Libraries like Dayjs and Luxon offer easy-to-read syntax and excellent time zone management.
- Some libraries like
date-fns
provide specific functions likestartOfDay
. - Explore their docs for updated methods and common practices.
Was this article helpful?