Dates in JS are difficult and it is easy to reach for an external library like Moment.
But is that true? No, but there are a few gotchas.
There are two “times” we need to concern ourselves with, these are.
- Local Time and Coordinated Universal Time (UTC). Local time refers to the time zone your computer is operating on.
- UTC is kinda like Greenwich Mean Time and from what dates and times relate to.
Unless you are doing something really funky the date object uses local time unless you explicitly request UTC. HOWEVER, there is one exception to this. That is creating a date with a string.
Create a date with a string
new Date("2020-11-04")
This is method uses a string to set the date. Pretty straight forward but creating a date with no time is a UTC date/time.
The problem is if your computer is operating in a time zone ahead or behind UTC the date could be out by a day.
SOLUTION 1: Always include hours and minutes as a minimum.
SOLUTION 2: Do not create date objects with strings, use a different method.
Create a date with arguments
new Date(2020, 7, 19, 8, 33)
Creating a date object by using arguments. The above has a value of :
Wed, 19 Aug 2020 08:33 // Local time!
If you look closely it is not really intuitive. August is the 8th month but is represented by the number 7. That is because in Javascript is zero indexed and January is 0 …. December is 11. Not much you can do about it so do not stress and just get on with it. Treat it as a feature, and you wont end up with a UTC time when you wanted a local time.
If you are wondering how to create a UTC date with arguments:
new Date(Date.UTC(2020, 11, 10)); // 10th November 2020 <whatever time it is now>
Create a date without arguments or string
new Date()
Will create a date object with the current local date and time.
Create a date with a timestamp
new Date(1604762586100); // Sat Nov 07 2020 15:23:06 GMT+0000
You can also create a date object using a timestamp. In JavaScript, a timestamp is the amount of milliseconds elapsed since 1 January 1970. I do not remember ever using this method.
Your can get the current timestamp with:
Date.now();
That should be pretty straight forward. The key takeaways are:
- Know that you are creating a local or UTC date object
- Maybe avoid creating a date object with a string
- Remember that months start at 0. January = 0 , December = 11