JavaScript provides a useful Date object that abstracts away a lot of the nitty gritty of working with dates directly. This is great because it allows us to represent moments in time and manipulate them with just a few lines of code.
JavaScript makes working with dates easy.
Creating a Date
Creating a date is extremely easy. Simply create a new Date object:
Because no parameters were passed in, JavaScript will just return the current date and time. This is a useful default, but it's also possible to create a date with a specific date and time.
Datestring
You can optionally pass in a string or a number to Date and it will give you back a different date and time. If you pass in a string, or a Datestring, it will be parsed with the Date.parse() method to give you back the Date object.
Let's say instead of today you wanted March 4, 2017, just pass it in:
JAVASCRIPT
const date = newDate("March 4, 2017");
console.log(date);
HTML
Sat Mar 04 2017 00:00:00 GMT-0500 (Eastern Standard Time)
Unix Time
In the field of computer science, there is a concept of Unix time. This arbitrarily decided moment in time is set to midnight on January 1st, 1970.
With that frame of reference in mind, if you pass in a number to a Date object, that number represents the number of milliseconds that have elapsed since then.
Here is one trillion milliseconds since then:
JAVASCRIPT
const date = newDate(1000000000000);
console.log(date);
HTML
Sat Sep 08 2001 21:46:40 GMT-0400 (Eastern Daylight Time)
The beauty of this format is that you can represent exact moments in time with a single number, and not have to worry about dates and strings and timezones, as you can derive all the information you need whenever you want. This is a great format for storing data in databases and cookies because it is just a number.
Multiple Parameters
Another way of creating new Date objects is by passing in 7 numbers. These numbers represent, in order, the year, month, day, hour, minute, second, and millisecond.