The JavaScript Date object
The Date object represents a single moment in time. Create one with new Date() for now, or pass a date string or numbers. Read parts with getFullYear(), getHours() and so on, and format with toLocaleDateString(). Watch the classic gotcha: months are zero-based, so January is 0.
Overview
The Date object handles dates and times. new Date() captures the current moment; new Date("2026-06-23") parses a date string; and new Date(year, month, day) builds one from parts. Internally a date is just a number — milliseconds since January 1, 1970 (the "Unix epoch") — which you can read with getTime().
You read the pieces with getter methods: getFullYear(), getMonth(), getDate() (day of the month), getDay() (day of the week), getHours(), getMinutes(). For display, the toLocale* methods are your friends — toLocaleDateString() and toLocaleTimeString() format a date according to the user's locale, which is far better than building strings by hand.
Two gotchas bite everyone. First, months are zero-based: getMonth() returns 0 for January and 11 for December, and the same when constructing — new Date(2026, 0, 1) is January 1st. (Confusingly, getDate() for the day is one-based.) Second, the native Date API is famously clunky for parsing and arithmetic, so for heavy date work many developers reach for the modern Temporal API or a library like date-fns.
Syntax
const now = new Date(); // current date & time
const d = new Date("2026-06-23"); // from a string
const d2 = new Date(2026, 5, 23); // June 23 (month is 0-based!)
now.getFullYear(); // e.g. 2026
now.getMonth(); // 0-11 (0 = January)
now.toLocaleDateString(); // locale-formatted
Example
<pre id="out" style="font:15px ui-monospace,monospace"></pre>
<script>
const now = new Date();
document.getElementById('out').textContent =
'year: ' + now.getFullYear() + '\n' +
'month: ' + (now.getMonth() + 1) + ' (getMonth is 0-based)\n' +
'local: ' + now.toLocaleDateString();
</script>
Best practices
- Remember months are zero-based:
0is January,11is December. - Format for display with
toLocaleDateString()/toLocaleTimeString()rather than building strings manually. - Use
getTime()(milliseconds) to compare or subtract dates. - For heavy parsing or date math, consider the modern
TemporalAPI or a library likedate-fns.
Frequently asked questions
How do I get the current date in JavaScript?
new Date(), which represents the current date and time.Why is getMonth() off by one?
getMonth() returns 0 for January through 11 for December. Add 1 for the human month number.How do I format a date nicely?
date.toLocaleDateString() or toLocaleString(), which format according to the user's locale.How do I compare two dates?
getTime() values (milliseconds), or subtract them: (d2 - d1) gives the difference in milliseconds.