Explain Codes LogoExplain Codes Logo

How to get start and end of day in Javascript?

javascript
time-zones
date-formatting
javascript-libraries
Alex KataevbyAlex Kataev·Oct 30, 2024
TLDR

Here's how to get sun-up and lights-out for 'today':

let sunUp = new Date(); sunUp.setHours(0, 0, 0, 0); // Sunrise, the rooster crows. let lightsOut = new Date(); lightsOut.setHours(23, 59, 59, 999); // Lights out, the owl hoots.

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:

let dawnUTC = new Date(); dawnUTC.setUTCHours(0, 0, 0, 0); // UTC Dawn, the world's rooster crows. let duskUTC = new Date(); duskUTC.setUTCHours(23, 59, 59, 999); // UTC Dusk, the world's owl hoots.

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 provides dayjs.utc().startOf('day') and dayjs.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 like startOfDay.
  • Explore their docs for updated methods and common practices.