The Date object is a built-in JavaScript feature. It lets you access the local time of the user's computer system through the browser. Additionally, the Date object comes with many methods for handling, altering, and formatting dates and times.
Before we can work with dates and times, we need to create a Date object. Unlike other built-in objects like arrays or functions, dates don't have a direct literal form. All date objects must be created using the Date constructor function, which is Date()
.
There are four different methods to create a Date object in JavaScript.
new Date()
SyntaxYou can declare a new Date object without giving it an initial value. When you do this, the date and time will automatically be set to the current date and time on the user's device where the script is executed.
var d = new Date();
document.write(d);
Another way to initialize a Date object is by providing these parameters separated by commas: year, month, day, hours, minutes, seconds, and milliseconds.
The year and month parameters are necessary, while the other parameters are optional.
var d = new Date(2018,0,31,14,35,20,50);
document.write(d);
This date actually represents January 31, 2018, at 14:35:20 and 50 milliseconds. You can skip the time part and just specify the date if you prefer.
In JavaScript, you can also create a Date object by passing a string that represents a date, or both date and time, as shown in the example below:
var d = new Date("31 January 2018");
document.write(d);
This date represents January 31, 2018. You can also use strings like Jan 31 2018, or many other valid variations, and JavaScript will handle it automatically.
You can create a Date object by passing the number of milliseconds since January 1, 1970, at 00:00:00 GMT. This point in time is known as the UNIX epoch because 1970 was the year when the UNIX operating system was officially launched. Here's an example:
var d = new Date(1517356800000);
document.write(d);
The date above represents Wednesday, January 31, 2018, 05:30:00 GMT+0530.
After creating a Date object instance, you can use its methods to perform various tasks like getting different parts of a date, setting or changing individual date and time values, etc. These methods are explained in detail in the following sections.
Note: JavaScript offers shortcuts known as "literals" for creating most native objects without needing to use the new
operator, such as new Object()
, new Array()
, etc.
To obtain the current date and time, create a new Date object without providing any parameters. This will generate an object set to the current date and time. Here's an example:
var now = new Date();
alert(now); // Display the current date and time
The output of this example will look something like this (depending on time zone offset):
The JavaScript Date object offers several methods, like toDateString()
, toLocaleDateString()
, etc., to create date strings in various formats. Here's an example:
var d = new Date();
alert(d.toDateString()); // Display an abbreviated date string
alert(d.toLocaleDateString()); // Display a localized date string
alert(d.toISOString()); // Display the ISO standardized date string
alert(d.toUTCString()); // Display a date string converted to UTC time
alert(d.toString()); // Display the full date string with local time zone
Similarly, you can use the toLocaleTimeString()
and toTimeString()
methods of the Date object to create time strings, as shown in the following example:
var d = new Date();
alert(d.toTimeString()); // Display the time portion of the date
alert(d.toLocaleTimeString()); // Display a localized time string
Once you have a Date object, you can use several methods to extract details such as the month, date, hours, or minutes. The following section explains the different methods for retrieving individual pieces of information from a Date object.
The Date object provides various methods like getFullYear()
, getMonth()
, getDate()
, etc., which allow you to extract specific date components such as the year, month, day of the month, etc., respectively. The following example illustrates how to retrieve specific date components from a Date object using these methods:
var d = new Date();
// Extracting date part
alert(d.getDate()); // Display the day of the month
alert(d.getDay()); // Display the number of days into the week (0-6)
alert(d.getMonth()); // Display the number of months into the year (0-11)
alert(d.getFullYear()); // Display the full year (four digits)
The getDay()
method returns a number representing the day of the week (from 0 to 6), where 0 represents Sunday, 1 represents Monday, and so on.
Similarly, the getMonth()
method returns the number of the month (from 0 to 11), where 0 represents January and 7 represents August.
Similarly, the Date object provides methods like getHours()
, getMinutes()
, getSeconds()
, getTimezoneOffset()
, etc., to retrieve the time components from the Date object.
var d = new Date();
// Extracting time part
alert(d.getHours()); // Display the number of hours into the day (0-23)
alert(d.getMinutes()); // Display the number of minutes into the hour (0-59)
alert(d.getSeconds()); // Display the seconds into the minute (0-59)
alert(d.getMilliseconds()); // Display the number of milliseconds into second (0-999)
alert(d.getTime()); // Display the number of milliseconds since 1/1/1970
alert(d.getTimezoneOffset()); // Display the time-zone offset (from Greenwich Mean Time) in minutes
The getHours()
method returns the hour of the day (from 0 to 23) in a 24-hour format. Therefore, at midnight, the method returns 0, and at 3:00 PM, it returns 15.
Note: Date objects also include methods to retrieve UTC components. Simply add "UTC" after "get," like getUTCDate()
, getUTCHours()
, getUTCMinutes()
, and so forth.
Besides retrieving date and time values, you can also set or modify them using JavaScript. This is commonly used in programs where you need to change the value of a date object from one specific date or time to another. Let's see how it's done.
The Date object provides methods like setFullYear()
, setMonth()
, and setDate()
to adjust the year, month, and date components of the Date object, respectively.
For example, in the following code snippet, we use the setFullYear()
method to update a variable storing the current date to two years in the future.
var d = new Date();
d.setFullYear(d.getFullYear() + 2);
alert(d); // Display future date
The output of the above example will resemble the following:
Similarly, you can utilize the setMonth()
method to adjust or change the month component of a Date object.
var d = new Date(); // Current date and time
d.setMonth(0); // Sets month to 0, January
document.write(d);
The setMonth()
method requires an integer value from 0 to 11. If you set a value greater than 11, the year value of the Date object will increase accordingly.
In essence, setting a value of 12 increments the year by 1 and sets the month to 0, as shown in the following example:
var d = new Date(2018, 5, 24); // June 24, 2018
d.setMonth(12); // Sets month to 12, new date will be January 24, 2019
document.write(d);
Similarly, you can adjust the date component of the Date object, as shown below:
var d = new Date(2018, 5, 24); // June 24, 2018
d.setDate(15); // Sets date to 15, new date will be June 15, 2018
document.write(d);
The setDate()
method requires an integer value from 1 to 31. Additionally, if you provide a value greater than the number of days in the current month, the month will be incremented. For example:
var d = new Date(2018, 5, 24); // June 24, 2018
d.setDate(36); // Sets day to 36, new date will be July 6, 2018
document.write(d);
Methods for adjusting time values are straightforward. The setHours()
, setMinutes()
, setSeconds()
, and setMilliseconds()
can be used to modify the hour, minutes, seconds, and milliseconds parts of the Date object, respectively.
Each method accepts integer values as parameters. Hours range from 0 to 23, minutes and seconds range from 0 to 59, and milliseconds range from 0 to 999. Here's an example:
var d = new Date(2018, 5, 24); // June 24, 2018 00:00:00
d.setHours(8);
d.setMinutes(30);
d.setSeconds(45);
d.setMilliseconds(600);
document.write(d);
The output of the above example will resemble the following: