Date() and Date.now()
I want to first quickly cover the difference between Date() and Date.now(). Both can give you the number of milliseconds since January 1st, 1970 UTC (Coordinated Universal Time / Universal Coordinated Time). So they are interchangeable, right? Not quite.
Date.now() is a static method (meaning, a method called on the class definition itself and not on an instantiation of the class) which produces a number – that number being the number of milliseconds since January 1st, 1970. And that’s all it is – a number.
Date() is an instantiation of the Date object which returns that Date object. You can get the number of milliseconds since January 1st, 1970 by calling the getTime() method, and that will return a number. However, since Date() is a Date object, you can now apply all the methods available to the Date object to get things like the current month, date, seconds, etc. These are things you cannot do with Date.now().
const nowDate = Date.now(); const myDate = new Date(); // the following two lines should print out the same number, or be very close, // depending upon the performance of your machine. console.log(nowDate); console.log(myDate.getTime()); // ...but you can't do the following with 'nowDate' console.log(myDate.getMonth()); // prints local month console.log(nowDate.getMonth()); // throws exception. getMonth() is not a function.
Bottom line: Use Date() if you plan to do any type of date manipulation, and Date.now() if you simply want a timestamp.
The Date Object Constructors
There are four ways to construct Dates:
This returns the current date/time specific to the locale of the user. As mentioned above, timing wise it returns the same time as using Date.now().
const myDate = new Date(); console.log(myDate.getFullYear); // prints "2020" assuming you run your code in the year 2020.
Returns the date/time associated with the number passed. This number will be the number of milliseconds since January 1st, 1070. Great to use if you happen to store Date information in your database in milliseconds.
// NOTE: These dates are printing for GMT. Your dates may be slightly different, // especially in the time section const date1 = new Date(1567419822000); console.log(date1); // prints Mon Sep 2nd 2019 10:23:42 AM const date2 = new Date(1600000000000); console.log(date2); // prints Sun Sep 13 2020 12:26:40 PM
Parses the string you supplied and attempts to interpret a date from it. WARNING: According to the Mozilla Development Network docs, using this constructor (and the associated static method Date.parse) is not recommended based upon variations in browsers. Personally, I will take that at face value and also not recommend this. However, do you own research and make up your own mind.
const date1 = new Date('2020-01-02'); console.log(date1); // prints Wed Jan 02 2020 00:00:00 const date2 = new Date('March 13, 2020'); console.log(date2); //prints Fri Mar 13 2020 00:00:00
This is the one I recommend using. By passing it a plethora of date and time arguments, you can manually create a Date instance that is associated with your local time. The arguments are:
- year (required)
- monthIndex (required. Note. See below for a gotcha!)
- day (optional, default 1)
- hours (optional, default 0)
- minutes (optional, default 0)
- seconds (optional, default 0)
- milliseconds (optional, default 0)
A word of caution on the ‘monthIndex’ argument: What you pass is not the number of the month on the calendar, but instead the index of the month, as if you were referencing an array. For example, on a calendar, January is Month #1, and December is Month #12. For the ‘monthIndex’ number, however, January is Month #0 and December is Month #11. Just be aware that you need to subtract 1 from the actual calendar month to get the correct ‘monthIndex’.
const date1 = new Date(2020, 8, 22, 13, 12, 11, 109); console.log(date1); //prints Tue Sep 22 2020 12:12:11 const date2 = new Date(2020, 0); console.log(date2); // prints Wed Jan 01 2020 00:00:00 (notice the defaults)
How about a little comparison?
You can even compare dates and find elapsed times between dates with some simple code.
For example, suppose you wanted to find out is one date is later than another date. That’s easy and simple to do with just a basic comparison:
const date1 = new Date(2020, 0, 10); // January 10th const date2 = new Date(2020, 2, 10); // March 10th console.log(date1 < date2); // prints 'true' console.log(date2 < date1); // prints 'false'
Or how about the elapsed time between two dates? Again, real simple. Just use math!
const date1 = new Date(2020, 0, 10); // January 10th const date2 = new Date(2020, 2, 10); // March 10th // using Math.abs() below means the number will always be positive // not matter the order of the dates are subtracted. console.log(Math.abs(date1 - date2)); // prints 5180400000
Now that you have the number of milliseconds between the dates, you can write your own routine to determine the year / month / days / hours / minutes / seconds / milliseconds that have elapsed. I’ve done a very quick one on the video that goes with this post – look at the end of this post for the video.
Bonus: The Temporal Object
If you work with the Date object for a while, you will start to notice a number of shortcomings – for instance, dealing with time zones, elementary or non-existent date manipulation and comparison functions, just to name a few.
So a number of years ago the Brains got together and decided to create an entirely new object, called the Temporal object, that will work with dates better than Date(). Not only will it create dates for you (as does Date), but now you can do things like:
- Get dates/times in different time zones
- Time duration
- Time “mathematics”, such as difference between two dates
- And much more!
Can you use it today? No. It’s still in what they call “Stage 2” proposal, where everybody comments on it and the tweak the code based upon the comments.
You can, however, take a look at what’s been done and even play around with it a little bit. Check out the links here: https://tc39.es/proposal-temporal/docs/index.html
Also, check out the video at the end of this article for a brief run-through of Temporal.
PLEASE READ! Feel free to play around with Temporal, but NEVER use it in production! It’s not ready.
You can see all of the above in the video edition of this post.
Date() is great if your application relies heavily upon the storage and manipulation of dates. It does have its shortcomings, so make sure you keep abreast of the new Temporal object – Coming Soon to a Browser/Node/Deno near you!
Web Tinkerer. No, not like Tinkerbell.