JavaScript dates

Every time I have anything to do with manipulating dates in JavaScript I need to stop and refresh my memory. Yes, there are amazing packages from Moment.js and Date-fns.

But why should I import a library just to a few simple things?

Here are my notes on dates (it is not an exhaustive list).

Time zones

There are 24 time zones mix in that many also have day light saving which adds/subtracts an hour. When a country does this is not constant around the world and is not fixed

So, in JavaScript there are two times:

  • Local = the time of the computer the code is running on
  • UTC = roughly the same as Greenwich Mean Time (GMT)

Date methods in JavaScript return Local time

In practice

Here I need to create a date range array. The range covers 30 days

const autoDays = () => {
      const daysInThePast = 30;
      const today = new Date();
      const pastDate = new Date(today);
      pastDate.setDate(today.getDate() - daysInThePast);
      return [
        pastDate.toISOString().substring(0, 10),
        today.toISOString().substring(0, 10)
      ];
    }

Explanation

  • Two ‘new Date()’ are used to avoid unwanted mutation
  • ‘today.getDate()’ returns the number part of the date. E.g. 29 in 29th July 2020
  • ‘pastDate.setDate(today.getDate() – daysInThePast)’ sets the date number. Notice how the number could be a negative or positive number. E.g. -10 or +36
  • JavaScript will correct the date to make sense. E.g. 36th July would become 5th August