Date & Time
In Javascript we can easily work with Date & Time using the Date class. To create an object of this type we use the new keyword, something that will be further explained later.
// Creating a Date object
var dateObj = new Date();
console.log(dateObj);
By doing this, we create an object with the current date and time formed by weekday, month, day, year, hours, minutes, seconds and timezone.
Methods of the Date object
| Method | Description |
|---|---|
| getDate() | Returns the day of the month (1 to 31) |
| getDay() | Returns the weekday (0 - Sunday to 6 - Saturday) |
| getFullYear() | Returns the full year (YYYY) |
| getMonth() | Returns the month (0 to 11) |
| getHours() | Returns the hours (0 to 23) |
| getMinutes() | Return the minutes (0 to 59) |
| getSeconds() | Returns the seconds (0 to 59) |
| getMilliseconds() | Returns the milliseconds (0 to 999) |
| getTime() | Returns the number of milliseconds since the Epoch(Jan 1st, 1970, 00:00:00) |
| setTime() | Creates a specific date from milliseconds since the epoch. |
Unix Epoch
The Epoch is something present in most programming languages. We can consider it the starting point of counting the time. This is useful to do calculations with date and time.
Javascript uses the Unix Epoch, which is: Jan 1st, 1970, 00:00:00, UTC.
var dateObj = new Date();
console.log(dateObj.getTime());
The getTime() method returns the number of milliseconds since the Epoch (Remember that 1 second = 1000 milliseconds). See the table below for a few conversions done with milliseconds:
| Time | Milliseconds (ms) |
|---|---|
| 1 second | 1.000 |
| 1 minute | 60.000 |
| 1 hour | 3.600.000 |
| 1 day | 86.400.000 |
| 1 year (365 days) | 31.536.000.000 |
How to calculate how many hours have passed since the Epoch?
var dateObj = new Date();
dateObj = dateObj.getTime();
var hours = dateObj / 3600000;
console.log(Math.floor(hours));
How to create specific dates
In the examples above we created date objects without passing any arguments, this is why they represented the current time. But we can also pass arguments to create specific dates.
var dateObj = new Date(2020,2,18);
console.log( dateObj );
We can also pass strings as arguments in three different formats:
var dateObj = new Date("2020-03-18");
console.log( dateObj );
Challenge: Calculating date intervals
If a product is ordered on March 26, 2020 and delivered on April, 02, 2020, how many days does it take to be delivered?
Delivery time: Show the number of days here