JS Date Get Methods
Once you have a Date, you read its pieces with get… methods. Each comes in local and UTC versions — pick deliberately.
Local-time getters
| Method | Returns |
|---|---|
getFullYear() | 4-digit year. |
getMonth() | 0–11 (January is 0). |
getDate() | Day of month, 1–31. |
getDay() | Day of week, 0 (Sun) – 6 (Sat). |
getHours / Minutes / Seconds / Milliseconds | Time pieces. |
getTime() | Epoch milliseconds. |
getTimezoneOffset() | Minutes from UTC (positive = behind UTC). |
UTC versions
Same names with UTC in the middle: getUTCFullYear(), getUTCMonth(), getUTCHours(), etc.
Example
JS
const now = new Date();
const local = `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, "0")}-${String(now.getDate()).padStart(2, "0")}`;
const utc = now.toISOString().slice(0, 10);
now.getDay(); // 0..6 ← weekday
["Sun","Mon","Tue","Wed","Thu","Fri","Sat"][now.getDay()];
now.getTimezoneOffset(); // e.g. 480 for PST (UTC-8)
Days between two dates
JS
function daysBetween(a, b) {
const MS = 86_400_000;
// UTC math avoids daylight-saving glitches
const u1 = Date.UTC(a.getFullYear(), a.getMonth(), a.getDate());
const u2 = Date.UTC(b.getFullYear(), b.getMonth(), b.getDate());
return Math.round((u2 - u1) / MS);
}
Gotcha:
getMonth() returns 0 for January. Forget the + 1 and your display dates are off by a month — one of the most-reported JS bugs ever.Example
Example
<!DOCTYPE html>
<html>
<body>
<p id="out"></p>
<script>
document.getElementById("out").textContent = "Hello from JS Date Get Methods!";
</script>
</body>
</html>
Try it Yourself »
Exercise
Get the year of a Date.
const y = d.
();
Two words concatenated, camelCase.
Discussion
Loading…