404 Not Found

404 Not Found


nginx

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.

📖 Summary

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.

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.

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>

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.

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

HTML
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Current Date and Time</title>
  <style>
    body { font-family: sans-serif; padding: 20px; text-align: center; }
    .clock { display: inline-block; padding: 24px 40px; background: #1a1a2e; color: #e0e0e0; border-radius: 12px; }
    .time { font-size: 48px; font-weight: bold; color: #00d4ff; font-family: monospace; }
    .date { font-size: 20px; margin-top: 8px; color: #a0a0c0; }
  </style>
</head>
<body>
  <h2>Live Clock</h2>
  <div class="clock">
    <div class="time" id="time">--:--:--</div>
    <div class="date" id="date">----/--/--</div>
  </div>
  <script>
    function updateClock() {
      const now = new Date();
      const h = String(now.getHours()).padStart(2, "0");
      const m = String(now.getMinutes()).padStart(2, "0");
      const s = String(now.getSeconds()).padStart(2, "0");
      document.getElementById("time").textContent = `${h}:${m}:${s}`;

      const y = now.getFullYear();
      const month = String(now.getMonth() + 1).padStart(2, "0");
      const d = String(now.getDate()).padStart(2, "0");
      const weekdays = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];
      document.getElementById("date").textContent = `${y}-${month}-${d} ${weekdays[now.getDay()]}`;
    }

    updateClock();
    setInterval(updateClock, 1000);
  </script>
</body>
</html>
▶ Try it Yourself

Example: Date Info Details

HTML
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Date Info</title>
  <style>
    body { font-family: sans-serif; padding: 20px; }
    table { border-collapse: collapse; margin: 16px 0; }
    td, th { border: 1px solid #ddd; padding: 10px 16px; text-align: left; }
    th { background: #4a90d9; color: #fff; }
    .note { background: #fff8e1; padding: 12px; border-radius: 6px; border-left: 4px solid #f0ad4e; margin: 16px 0; }
  </style>
</head>
<body>
  <h2>Date Object Method Return Values</h2>
  <div id="output"></div>
  <script>
    const now = new Date();
    const data = [
      ["getFullYear()", now.getFullYear(), "4-digit year"],
      ["getMonth()", now.getMonth(), "0-11 (add 1 for actual month)"],
      ["getDate()", now.getDate(), "1-31 (day of the month)"],
      ["getDay()", now.getDay(), "0-6 (0 = Sunday)"],
      ["getHours()", now.getHours(), "0-23"],
      ["getMinutes()", now.getMinutes(), "0-59"],
      ["getSeconds()", now.getSeconds(), "0-59"],
      ["getTime()", now.getTime(), "Timestamp (milliseconds)"],
    ];

    document.getElementById("output").innerHTML = `
      <table>
        <tr><th>Method</th><th>Return Value</th><th>Description</th></tr>
        ${data.map(r => `<tr><td><code>${r[0]}</code></td><td>${r[1]}</td><td>${r[2]}</td></tr>`).join("")}
      </table>
      <div class="note">
        <strong>Months are zero-indexed</strong>: getMonth() returns ${now.getMonth()}, but the actual month is ${now.getMonth()+1}.
        <strong>getDay() is the weekday</strong>: it returns ${now.getDay()} (${["Sun","Mon","Tue","Wed","Thu","Fri","Sat"][now.getDay()]}), not the date!
      </div>
    `;
  </script>
</body>
</html>
▶ Try it Yourself

Example: Countdown Timer

HTML
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Countdown</title>
  <style>
    body { font-family: sans-serif; padding: 20px; text-align: center; }
    .countdown { display: inline-block; padding: 24px; background: linear-gradient(135deg, #667eea, #764ba2); color: #fff; border-radius: 12px; margin: 16px 0; }
    .countdown h3 { margin: 0 0 12px; font-size: 18px; }
    .timer { display: flex; gap: 16px; justify-content: center; }
    .unit { text-align: center; }
    .number { font-size: 40px; font-weight: bold; font-family: monospace; }
    .label { font-size: 12px; opacity: 0.8; }
    .input-row { margin: 16px 0; }
    input { padding: 8px 12px; font-size: 16px; border: 2px solid #ccc; border-radius: 6px; }
    button { padding: 8px 20px; font-size: 16px; border: none; border-radius: 6px; cursor: pointer; background: #4a90d9; color: #fff; }
    button:hover { background: #357abd; }
  </style>
</head>
<body>
  <h2>Countdown to Target Date</h2>
  <div class="input-row">
    <input type="datetime-local" id="target" />
    <button id="startBtn">Start Countdown</button>
  </div>
  <div class="countdown" id="countdown" style="display:none;">
    <h3 id="targetLabel">Time remaining</h3>
    <div class="timer">
      <div class="unit"><div class="number" id="days">0</div><div class="label">Days</div></div>
      <div class="unit"><div class="number" id="hours">0</div><div class="label">Hours</div></div>
      <div class="unit"><div class="number" id="minutes">0</div><div class="label">Min</div></div>
      <div class="unit"><div class="number" id="seconds">0</div><div class="label">Sec</div></div>
    </div>
  </div>
  <script>
    const defaultTarget = new Date();
    defaultTarget.setDate(defaultTarget.getDate() + 7);
    const dateStr = defaultTarget.toISOString().slice(0, 16);
    document.getElementById("target").value = dateStr;

    let timer = null;

    document.getElementById("startBtn").addEventListener("click", function() {
      const target = new Date(document.getElementById("target").value);
      if (isNaN(target.getTime())) {
        alert("Please select a valid date and time");
        return;
      }
      document.getElementById("countdown").style.display = "inline-block";
      document.getElementById("targetLabel").textContent =
        `Time until ${target.toLocaleString()}`;

      if (timer) clearInterval(timer);

      function update() {
        const now = Date.now();
        const diff = target.getTime() - now;
        if (diff <= 0) {
          document.getElementById("days").textContent = "0";
          document.getElementById("hours").textContent = "0";
          document.getElementById("minutes").textContent = "0";
          document.getElementById("seconds").textContent = "0";
          document.getElementById("targetLabel").textContent = "Time's up!";
          clearInterval(timer);
          return;
        }
        const days = Math.floor(diff / (1000 * 60 * 60 * 24));
        const hours = Math.floor((diff % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
        const minutes = Math.floor((diff % (1000 * 60 * 60)) / (1000 * 60));
        const seconds = Math.floor((diff % (1000 * 60)) / 1000);
        document.getElementById("days").textContent = days;
        document.getElementById("hours").textContent = String(hours).padStart(2, "0");
        document.getElementById("minutes").textContent = String(minutes).padStart(2, "0");
        document.getElementById("seconds").textContent = String(seconds).padStart(2, "0");
      }

      update();
      timer = setInterval(update, 1000);
    });
  </script>
</body>
</html>
▶ Try it Yourself

Example: Date Difference Calculator

HTML
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Date Difference</title>
  <style>
    body { font-family: sans-serif; padding: 20px; }
    .calc { max-width: 500px; margin: 16px auto; }
    .row { margin: 12px 0; }
    label { display: inline-block; width: 100px; font-weight: bold; }
    input { padding: 8px 12px; font-size: 16px; border: 2px solid #ccc; border-radius: 6px; }
    button { padding: 8px 20px; font-size: 16px; border: none; border-radius: 6px; cursor: pointer; background: #5cb85c; color: #fff; margin-top: 8px; }
    button:hover { background: #449d44; }
    .result { margin-top: 16px; padding: 16px; background: #f0f7ff; border-radius: 8px; border: 2px solid #4a90d9; }
    .result div { margin: 4px 0; }
  </style>
</head>
<body>
  <h2 style="text-align:center;">Date Difference Calculator</h2>
  <div class="calc">
    <div class="row">
      <label>Start Date:</label>
      <input type="date" id="start" />
    </div>
    <div class="row">
      <label>End Date:</label>
      <input type="date" id="end" />
    </div>
    <div style="text-align:center;">
      <button id="calcBtn">Calculate</button>
    </div>
    <div class="result" id="result" style="display:none;"></div>
  </div>
  <script>
    const today = new Date();
    const lastMonth = new Date();
    lastMonth.setMonth(lastMonth.getMonth() - 1);
    document.getElementById("start").value = lastMonth.toISOString().slice(0, 10);
    document.getElementById("end").value = today.toISOString().slice(0, 10);

    document.getElementById("calcBtn").addEventListener("click", function() {
      const start = new Date(document.getElementById("start").value);
      const end = new Date(document.getElementById("end").value);

      if (isNaN(start.getTime()) || isNaN(end.getTime())) {
        alert("Please select valid dates");
        return;
      }

      const diffMs = Math.abs(end - start);
      const diffDays = Math.floor(diffMs / (1000 * 60 * 60 * 24));
      const diffHours = Math.floor(diffMs / (1000 * 60 * 60));
      const diffMinutes = Math.floor(diffMs / (1000 * 60));
      const diffWeeks = Math.floor(diffDays / 7);

      document.getElementById("result").style.display = "block";
      document.getElementById("result").innerHTML = `
        <div><strong>Days:</strong> ${diffDays}</div>
        <div><strong>Hours:</strong> ${diffHours}</div>
        <div><strong>Minutes:</strong> ${diffMinutes}</div>
        <div><strong>Approximately:</strong> ${diffWeeks} weeks and ${diffDays % 7} days</div>
      `;
    });
  </script>
</body>
</html>
▶ Try it Yourself

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

📝 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.
100%

🙏 帮我们做得更好

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

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