JavaScript: JavaScript Dates

Last updated: 2026-10-13

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.

Related Date Methods:getFullYear() toISOString() getMonth() getHours() Date.now() getDate() getDay() Date set

1. Creating and Manipulating Date Objects

(1) Creating Date Objects

Four common ways to create a Date:

HTML
<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:

HTML
<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.

HTML
<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:

HTML
<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

Related Date Methods:getFullYear() toISOString() getMonth() getHours() Date.now() getDate() getDay() Date set

❓ FAQ

Q Why does getMonth() require adding 1?
A Because Java's Date class was designed this way, and JavaScript inherited that "tradition." Everyone agrees it's a silly design, but it can't be changed — too much existing code depends on this behavior. Just memorize it.
Q Is there a difference between new Date("2025-06-19") and new Date(2025, 5, 19)?
A Yes. String-parsed dates default to UTC midnight, while the parameter form uses local time. The displayed time can differ by 8 hours (for UTC+8). If you only care about the date and not the time, the parameter form is safer.
Q How do I calculate someone's age?
A Subtract their birth year from the current year, then check if their birthday has passed this year: if the current month is less than the birth month, or the months are equal but the current day is less than the birth day, subtract 1 from the age.

📖 Summary

📝 Exercises

  1. Write a function formatDate(date) that returns a string in the format "YYYY-MM-DD (Weekday)". Make sure months and days are zero-padded.
  2. Write a function getAge(birthday) that takes a date string (e.g., "2000-03-15") and returns the current age in full years.
  3. 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.
Web-Tutorial.com

Web-Tutorial Tech Team

A team of developers maintaining programming tutorials. Each tutorial is written and reviewed by developers with expertise in that field. We work to keep our content accurate and reliable — if you spot an issue, please let us know.

100%

🙏 帮我们做得更好

我们是刚上线的编程教程站,几个人的小团队,精力有限。页面虽经检查,难免还有疏漏——链接失效、排版错乱、内容有误、语言生硬……

如果您发现了,麻烦告诉我们,我们会在收到反馈后第一时间进行修复,再次感谢您的光临 🙏