Main methods to retrieve date and time from the Date object.
Method | Description |
---|---|
getFullYear() | Retrieves the year |
getMonth() | Retrieves the month as a number from 0 to 11 (0 is January) |
getDate() | Retrieves the day of the month |
getDay() | Retrieves the day of the week as a number from 0 to 6 (0 is Sunday) |
getHours() | Retrieves the hour |
getMinutes() | Retrieves the minutes |
getSeconds() | Retrieves the seconds |
getMilliseconds() | Retrieves the milliseconds as a number from 0 to 999 |
getTimezoneOffset() | Retrieves the time difference from UTC in minutes |
getTime() | Retrieves the time in milliseconds since January 1, 1970, 00:00:00 UTC |
setFullYear(year) | Sets the year (Gregorian calendar) |
setMonth(month) | Sets the month as a number from 0 to 11 |
setDate(day) | Sets the day of the month |
setHours(hour) | Sets the hour |
setMinutes(minutes) | Sets the minutes |
setSeconds(seconds) | Sets the seconds |
setMilliseconds(milliseconds) | Sets the milliseconds as a number from 0 to 999 |
setTime(milliseconds) | Sets the time in milliseconds since January 1, 1970, 00:00:00 UTC |
Example:
var now = new Date();
var year = now.getFullYear();
var month = now.getMonth();
var date = now.getDate();
var hour = now.getHours();
var min = now.getMinutes();
var output = year + '/' + (month + 1) + '/' + date + ' ' + hour + ':' + min;
document.getElementById('time').textContent = output;
HTML:
<p>Date and Time: <span id="time"></span></p>