JavaScript Date Get Methods
Date get methods retrieve specific parts of a date, such as the year, month, day, hour, minute, and second. These methods help you isolate and use date components effectively.
Key Topics
Basic Get Methods
Methods like getFullYear(), getMonth(), and getDate() return various components of the date in local time.
let d = new Date();
console.log(d.getFullYear());
console.log(d.getMonth()); // 0-based index for months
console.log(d.getDate());
Output
> 2021 (example year)
> 5 (if June, since January is 0)
> 21 (day of the month)
Explanation: These methods extract specific parts of the current date. Note that months start at 0 (January) and go up to 11.
UTC Get Methods
Similar methods exist for UTC time, like getUTCFullYear(), getUTCMonth(), and getUTCDate(), which return components based on UTC instead of local time.
console.log(d.getUTCFullYear());
console.log(d.getUTCMonth());
console.log(d.getUTCDate());
Output
> 2021 (UTC year)
> 5 (UTC month index)
> 21 (UTC day of the month)
Explanation: UTC methods return date components as if you were in the UTC time zone, ignoring local offsets.
JavaScript Usage in DOM
This DOM-based example shows how to retrieve date components and display them on the webpage.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Date Get Methods in DOM</title>
</head>
<body>
<h1>Date Get Methods Demo</h1>
<button onclick="showDateParts()">Show Date Parts</button>
<p id="output"></p>
<script>
function showDateParts() {
let now = new Date();
let year = now.getFullYear();
let month = now.getMonth() + 1; // adjusting for 0-based index
let day = now.getDate();
document.getElementById("output").textContent = `Year: ${year}, Month: ${month}, Day: ${day}`;
}
</script>
</body>
</html>
Key Takeaways
- Local Time:
getFullYear(),getMonth(),getDate()return local date parts. - UTC Time:
getUTCFullYear(),getUTCMonth(),getUTCDate()return UTC-based values. - DOM Integration: Display extracted date components on webpages.