Find the Current Date
const date = new Date(); console.log(date);
>> Sun Feb 02 2020 08:17:01 GMT-0800 (Pacific Standard Time)
It is also possible to create a date object for a different time than right now by passing in an Epoch Time as the argument when creating a new date object
const exampleDate = new Date(31567796000); console.log(exampleDate);
>> Fri Jan 01 1971 00:49:56 GMT-0800 (Pacific Standard Time)
Any time between roughly -271,000 BCE and 275,000 CE can be set using the date object.
Passing in Date Values
Alternatively we can create dates given a date string or by passing in current date values in the date creation. Both examples below will return approximately the same date as the one above.
const usingDateString = new Date("January 01 1971 00:49"); // string argument is "Month day year time" const usingDateValues = new Date(1971, 0, 1, 0, 49, 0, 0); // values argument is year, month, day, hour, minute, second, ms
Date Method Syntax
Logging the date alone will give us plenty of information, however there are methods we can use to display individual pieces of data for logging or output. The following will save the current year to a variable
const year = new Date().getFullYear();
Get / Set Methods
The following are some useful methods available to a date instance. This should be enough to represent any time or date. Not all methods are intuitive, for example getDay and getMonth are both zero-indexed instead of starting from 1 like getDate.
|getTime()||Epoch Time||13 digit number|
|getDay()||Day of Week||0-6|
|getFullYear()||Current Year||4 digit number|
For each of the get methods, we also have access to a corresponding set method. This can be useful when you need to update a date object, or have a particular time to set.
const date = new Date(); date.setFullYear(-250000); console.log(date);
>> Wed Feb 02 -250000 09:33:00 GMT-0752 (Pacific Standard Time)
Using Locale Date Strings
Sometimes converting the date object to a simple Date and/or Time string will suffice. The following date methods will convert your date object to a more readable version.
|toLocaleString()||Time and Date||2/2/2020, 8:38:33 AM|
|toLocaleTimeString()||Current Time||8:38:33 AM|
Adding and Subtracting Dates
A combination of the
set methods of time can be used to change dates. For example
const date = new Date(); console.log(date); // Sun Feb 02 2020 20:00:11 GMT-0800 (Pacific Standard Time) date.setHours(date.getHours() - 10); console.log(date); // Subtracted 10 hours // Sun Feb 02 2020 10:01:25 GMT-0800 (Pacific Standard Time) date.setMonth(date.getMonth() + 5); console.log(date); // Added 5 months
>> Thu Jul 02 2020 10:01:25 GMT-0700 (Pacific Daylight Time)