Creating a Date Object
You can create a Date object using the
new keyword followed by
Date object can be constructed with four different sets of arguments:
let date1 = new Date(); // current date and time let date2 = new Date(year, month, day, hours, minutes, seconds, milliseconds); // specified date and time let date3 = new Date(milliseconds); // number of milliseconds since Unix Epoch let date4 = new Date(dateString); // date string in a format recognized by the Date.parse() method
The Date object comes with a variety of methods to get and set different parts of the date and time, and to convert the date to a string in various formats.
These methods are used to get parts of a date:
let date = new Date(); date.getFullYear(); // Get the four-digit year date.getMonth(); // Get the month as a number (0-11) date.getDate(); // Get the day as a number (1-31) date.getHours(); // Get the hour (0-23) date.getMinutes(); // Get the minute (0-59) date.getSeconds(); // Get the second (0-59) date.getMilliseconds(); // Get the millisecond (0-999) date.getTime(); // Get the time (milliseconds since January 1, 1970)
These methods are used to set parts of a date:
let date = new Date(); date.setFullYear(year); // Set the year date.setMonth(month); // Set the month date.setDate(day); // Set the day of the month date.setHours(hours); // Set the hours date.setMinutes(minutes); // Set the minutes date.setSeconds(seconds); // Set the seconds date.setMilliseconds(milliseconds); // Set the milliseconds date.setTime(milliseconds); // Set the time
These methods are used to convert a Date object to a string:
let date = new Date(); date.toString(); // Convert a Date object to a string date.toUTCString(); // Convert a Date object to a string, according to universal time date.toISOString(); // Returns the date as a string, using the ISO standard date.toJSON(); // Returns the date as a string, formatted as a JSON date
Did you find this article valuable?
Support 0xTristan by becoming a sponsor. Any amount is appreciated!