Date
The JavaScript Date
object provides methods for dealing with dates and times.
In computing, dates and times are often internally represented as the number of milliseconds since January 1, 1970 00:00:00 UTC. This is a somewhat arbitrary choice, but lots of computer systems use this method, as it provides millisecond precision and is consistent internationally, avoiding the need to take in to account geographic time zones. It derives from old UNIX-based computer systems, so the January 1 1970 date is often referred to as the "UNIX epoch". For example at time of writing on 26th November 2021, the current time is 1637930545179 milliseconds since the UNIX epoch.
When displaying dates as strings, it will use the local language and formatting style, as well as the local timezone, based on your system settings. So note the particular format shown in the examples below may differ from what you see.
Try out the following lines of code in the browser console.
// Try entering in to the browser console:
// Using just Date() returns a string of the current date and time
Date() // Fri Nov 26 2021 12:38:13 GMT+0000 (Greenwich Mean Time)
// Date.now() provides the current time in milliseconds since the UNIX epoch
Date.now() // 1637930545179
// new Date() creates a new object representing the
// current date. Note while this creates an object,
// the console will show it as a date and time.
new Date() // Fri Nov 26 2021 12:38:13 GMT+0000 (Greenwich Mean Time)
// new Date(time) creates a Date object using the
// time in milliseconds since the UNIX epoch.
new Date(1637930545179) // Fri Nov 26 2021 12:38:13 GMT+0000 (Greenwich Mean Time)
// new Date(year, monthIndex), with optional additional parameters up to
// new Date(year, monthIndex, day, hours, minutes, seconds, milliseconds)
// creates a Date object with the given date and time.
// NOTE: 'monthIndex' is 0-based (0 being January), but 'day' is 1-based.
// Mon Nov 01 2021 00:00:00 GMT+0000 (Greenwich Mean Time)
new Date(2021, 10)
// Tue Nov 23 2021 00:00:00 GMT+0000 (Greenwich Mean Time)
new Date(2021, 10, 23)
// Tue Nov 23 2021 11:53:12 GMT+0000 (Greenwich Mean Time)
new Date(2021, 10, 23, 11, 53, 12)
Here is a code sample you can try in Construct that demonstrates a few more methods of Date
objects to get the day, month and year of the current date as numbers (but note the month is zero-based, so we add 1 to it to start with January as 1 instead of 0).
// Get a Date object representing the current time
let currentDate = new Date();
// Log the day, month and year
// NOTE: the month is zero-based (0 is January) so we add 1 to it
console.log(`The day is ${currentDate.getDate()}`);
console.log(`The month is ${currentDate.getMonth() + 1}`);
console.log(`The year is ${currentDate.getFullYear()}`);
There's lots more you can do with Date
in JavaScript. See the Date MDN documentation for more.