CHAPTER 6The Date Class
The Date
class stores dates as an integer, the "epoch". This number counts the number of seconds that have passed since January 1st, 1970. All operations are done to this number, which is converted back to year, month, day, etc. on demand. Also, Date
s are stored in UTC (Coordinated Universal Time), and therefore converted to local time on demand as well.
Creating a Date
Creating dates from strings sets them as UTC time:
new Date(); // current computer time
new Date("2024-03-05");
new Date("2024-03-05 05:55:41.123");
Creating dates from integers means converting them from local time:
new Date(2024, 0, 1); // '2023-12-31 23:00:00' since we are GMT+1
Copying dates can be done by passing them in the constructor:
const d = new Date(`2000-01-01`);
const e = new Date(d); // copy of 'd'
Methods to get parts of a Date
getTime | Epoch |
getMilliseconds | Milliseconds |
getMinutes | Minutes |
getHours | Hours |
getDate | Day of the Month |
getDay | Day of the Week (0 to 7) |
getMonth | Month (Careful! 0 - 11) |
getYear | Year |
There are methods to get the same parts but for the UTC date: getUTCDate
, getUTCDay
, getUTCHours
, etc.
Time intervals
When using Date
as numbers (in subtractions or comparisons), they are autoconverted to the underlying number (the Epoch), so it is safe to subtract Date
s and compare them.
const start = new Date(`2024-01-01`);
const end = new Date(`2024-02-13`);
if (end < start) {
throw new Error(`The end date is before the start!`);
}
const MINUTE = 60 * 1000;
const HOUR = 60 * MINUTE;
const DAY = 24 * HOUR;
const timeDif = end - start; // equivalent end.getTime() - start.getTime()
const days = timeDif / DAY;
const hours = (timeDif % DAY) / HOUR;
console.log(`${days} days and ${hours} hours`);
Adding or subtracting time
Instead of having to use milliseconds for operations like adding or subtracting time periods from a Date
, we can use another property of Date
s: if you set any part of a date to a value out of bounds, its value will be autocorrected.
new Date(2024, 0, 52) // -> 2024-02-20T23:00:00.000Z
So, setting the 52nd of January will actually be the 20th of February. Using this, we can add a certain number of days or hours to a date:
const d = new Date();
d.setDate(d.getDate() + 2); // Two days from now
const e = new Date(d);
e.setHours(e.getHours() + 36); // 36 hours after 'd'