JavaScript provides a Date object that can be used to display date and time on the web pages according to the browser time zone. In this JavaScript tutorial, we will learn how to work with JS Date objects.
JavaScript Date
To represent Date data in JavaScript we generally use the built-in date object, which can output the current date according to the browser date time zone.
Syntax
Example
Output
To create a date object we use the new keyword followed by the Date() object. By default, the Date() object to print the current date & time in the following format
Create Date Object
We can create different Date objects with the help of
new Date()
constructor. And there are four different syntaxes we can follow to create a date-time object.
Syntax
Now let's discuss all these 4 different syntaxes to create date objects.
new Date()
The
new Date()
statement is used to create a date object of the current time.
Example
new Date(year, month, date, hours, ...)
We can also create a specific date and time object using the new Date() constructor by specifying the 7 parameters.
Syntax
Example
Output
JavaScript count Months from 0 to 11, parameter value 0 represents Jan, and 11 represents Dec. All the Date parameters values are optional, and by default, their value is maximized by their time limit. We can also create a manual date object by only specifying the date and month parameters.
Example
We can not omit the month parameter values when creating a manual date object with years and month, else the Date object will treat the single year value as milliseconds that we will cover in the further section.
new Date(milliseconds)
We can also create a date from milliseconds, where the 0 milliseconds represent the Following date time.
Example
The reason why we can not pass only a single year parameter value to the Date object is becaue it will treat the only year value as milliseconds.
new Date(string date)
We can also use the string representation to convert string Date data to a proper JS date object.
Example
Output
Summary
-
To create a new date object we can use the
new Date()
constructor. - If we do not specify any parameter value to the Date() object it returns the current date and time.
- We can either use the manual date, milliseconds, or string date format to create a new manual date object.
People are also reading: