0% completed
The Date
object in JavaScript is used to work with dates and times. It allows developers to get the current date
and time
, create specific dates, and manipulate date data, which is crucial for applications that rely on temporal information, such as calendars, reminders, and time tracking tools.
The JavaScript Date
object can be instantiated using various syntaxes, each serving different purposes based on the parameters provided. Here's a closer look at each syntax:
new Date() new Date(milliseconds) new Date(datestring) new Date(year,month,date, [hour,minute,second,millisecond ])
new Date()
Date
object with the current date and time.new Date(milliseconds)
Date
object based on the number of milliseconds since January 1, 1970, UTC.new Date(dateString)
Date
object representing the specified date and time.Date.parse()
method.new Date(year, month, date[, hour, minute, second, millisecond ])
Date
object with the specified date and time. year
and month
parameters are required, while the rest are optional.month
is 0-indexed (0 for January, 11 for December).Here are some essential Date methods grouped by their functionality:
Method | Description |
---|---|
getDate() | Returns the day of the month (1-31). |
getDay() | Returns the day of the week (0-6). |
getFullYear() | Returns the year. |
getHours() | Returns the hour (0-23). |
getMilliseconds() | Returns the milliseconds (0-999). |
getMinutes() | Returns the minutes (0-59). |
getMonth() | Returns the month (0-11). |
getSeconds() | Returns the seconds (0-59). |
getTime() | Returns the number of milliseconds since Jan 1, 1970. |
getTimezoneOffset() | Returns the time difference between UTC and Local Time in minutes. |
getUTCDate() | Returns the day of the month (UTC) (1-31). |
(And many more UTC methods corresponding to the local time methods) | |
setDate() | Sets the day of the month. |
setFullYear() | Sets the year. |
setHours() | Sets the hour. |
setMilliseconds() | Sets the milliseconds. |
setMinutes() | Sets the minutes. |
setMonth() | Sets the month. |
setSeconds() | Sets the seconds. |
setTime() | Sets the time (milliseconds since Jan 1, 1970). |
(And corresponding setUTC... methods) | |
toDateString() | Converts the date portion to a readable string. |
toISOString() | Returns the ISO string format of the date. |
toLocaleDateString() | Returns the date portion in a locale-specific format. |
toString() | Converts the Date object to a string. |
toTimeString() | Converts the time portion of a Date object to a string. |
valueOf() | Returns the primitive value of a Date object. |
Example 1: Getting the Current Date and Time
Example 2: Setting and Getting Specific Date Components
Example 3: Calculating the Difference Between Two Dates
.....
.....
.....