JavaScript: JavaScript Dates
JavaScript uses the Date object to work with dates and times. Think of it as a digital watch — it shows the current time, lets you set any moment, and can calculate the difference between two times.
1. Creating and Manipulating Date Objects
(1) Creating Date Objects
Four common ways to create a Date:
<!-- Script tag -->
<script>
console.log(new Date()); // Current date and time
console.log(new Date("2025-06-19")); // Date string
console.log(new Date(2025, 5, 19, 10, 30, 0)); // Year, month, day, hours, minutes, seconds
console.log(new Date(1718764800000)); // Timestamp (milliseconds)
</script>
Big gotcha: Months are zero-indexed! 0 = January, 11 = December. In new Date(2025, 5, 19), the 5 means June, not May. This is arguably the most criticized design decision in the Date object — period.
(2) Getting Date and Time
| Method | Returns | Note |
|---|---|---|
getFullYear() |
4-digit year | Don't use getYear() — it's deprecated |
getMonth() |
0–11 | Add 1 for the actual month |
getDate() |
1–31 | Day of the month |
getDay() |
0–6 | 0 = Sunday, not Monday! |
getHours() |
0–23 | — |
getMinutes() |
0–59 | — |
getSeconds() |
0–59 | — |
getDay() returns the day of the week, not the day of the month — use getDate() for that. Beginners often mix these up.
(3) Setting Date and Time
There's a matching set of set methods: setFullYear(), setMonth(), setDate(), setHours(), setMinutes(), setSeconds(). Values automatically roll over when set:
<!-- Script tag -->
<script>
const d = new Date(2025, 5, 19);
d.setDate(32); // Automatically becomes July 2
console.log(d.toLocaleDateString());
</script>
(4) Formatting Dates
| Method | Example Output |
|---|---|
toLocaleDateString() |
"6/19/2025" |
toLocaleTimeString() |
"10:30:00 AM" |
toLocaleString() |
"6/19/2025, 10:30:00 AM" |
These methods automatically format based on the browser's locale.
(5) Timestamps and Calculating Time Differences
A timestamp is the number of milliseconds elapsed since January 1, 1970 00:00:00 UTC.
<!-- Script tag -->
<script>
console.log(Date.now()); // Get current timestamp
console.log(new Date().getTime()); // Same as above
</script>
The core approach to calculating time differences: subtract two timestamps to get the millisecond difference, then convert:
<!-- Script tag -->
<script>
const start = Date.now();
for (let i = 0; i < 1000000; i++) {} // Simulate some operation
const end = Date.now();
const diff = end - start; // Milliseconds
const diffSeconds = diff / 1000; // Seconds
console.log("Time elapsed: " + diff + "ms (" + diffSeconds + " seconds)");
</script>
▶ Example: Displaying Current Date and Time
▶ Try it Yourself▶ Example: Date Info Details
▶ Try it Yourself▶ Example: Countdown Timer
▶ Try it Yourself▶ Example: Date Difference Calculator
▶ Try it Yourself❓ FAQ
new Date() returns a Date object, so you can call methods like getFullYear() and getMonth() on it; Date.now() directly returns the current timestamp in milliseconds. If you only need to record or compare points in time, Date.now() is lighter; use a Date object when you need fields like year, month, and day.new Date("2025-06-19") come out one day off?"2025-06-19" is parsed as UTC midnight per the ISO spec, so in UTC+8 it displays as June 19 08:00, but in negative time zones methods like getDate() may give the previous day. To create it in local time, the argument form new Date(2025, 5, 19) is more reliable.yyyy-mm-dd formatted date in JavaScript?new Date(timestamp) to turn the timestamp into a Date object, then take getFullYear(), getMonth()+1, and getDate() and pad them with zeros before joining. Note that getMonth() starts at 0, so you must add 1; you can also use toISOString().slice(0, 10), but that gives a UTC date, which may differ from the local date across time zones.📖 Summary
- Create Date objects with
new Date(),new Date(2024, 0, 1), ornew Date("2024-01-01") - Get methods:
getFullYear/getMonth/getDate/getDay/getHours/getMinutes/getSeconds - Set methods modify the Date object in place
- Format dates with
toLocaleDateString(),toISOString(), or manual concatenation - Timestamps are milliseconds; use
Date.now()for current timestamp, add/subtract for date math
📝 Exercises
- Write a function
formatDate(date)that returns a string in the format"YYYY-MM-DD (Weekday)". Make sure months and days are zero-padded. - Write a function
getAge(birthday)that takes a date string (e.g., "2000-03-15") and returns the current age in full years. - Build a "time ago" feature: given a past date, display "X years, X months, X days ago" or "X days ago" or "X hours ago" — automatically choosing the appropriate format based on the time difference.