Smart Systems for Home

Plain how-to guides for smart home, security and home Wi-Fi

How to Get Current Date and Time in JavaScript

· 5 min read · Home Tech

In this article
  1. What You'll Need
  2. Step-by-Step
  3. Common Mistakes
  4. Tips
  5. Troubleshooting
  6. Frequently Asked Questions

Getting the current date and time is one of the most common tasks in JavaScript, whether you're building a timestamp for a blog post, a countdown timer, or a scheduling app. The built-in Date object gives you everything you need, but its API can be a little quirky. This guide walks you through the standard methods, how to format the output, and how to avoid the classic pitfalls like timezone confusion.

What You'll Need

  • A web browser's console (press F12 or right-click → Inspect → Console) or any JavaScript environment like Node.js.
  • Basic familiarity with JavaScript syntax (variables, functions, objects).

Step-by-Step

  1. Create a new Date object – The simplest way to get the current date and time is to instantiate the Date object without any arguments. This automatically captures the current moment in your system's local timezone.
    const now = new Date();
  2. Get the full date and time as a string – If you just need a quick, human-readable version, call toString() or rely on implicit conversion.
    console.log(now.toString()); // e.g. "Tue Apr 15 2025 14:30:45 GMT+0200 (Central European Summer Time)"
  3. Extract individual components – Use the getter methods to pull out the year, month, day, hour, etc. Remember that months are zero-indexed (January is 0, December is 11).
    const year = now.getFullYear();
    const month = now.getMonth() + 1; // add 1 to get 1-12
    const day = now.getDate();
    const hours = now.getHours();
    const minutes = now.getMinutes();
    const seconds = now.getSeconds();
  4. Format a custom date string – Combine the components into your own format, padding single digits with a leading zero if needed.
    function pad(n) { return n < 10 ? '0' + n : n; }
    const formatted = `${year}-${pad(month)}-${pad(day)} ${pad(hours)}:${pad(minutes)}:${pad(seconds)}`;
    console.log(formatted); // "2025-04-15 14:30:45"
  5. Get the timestamp (milliseconds since Unix epoch) – For calculations, comparisons, or storing in databases, the numeric timestamp is often more useful. Use getTime() or Date.now().
    const timestamp = now.getTime();
    const timestampNow = Date.now();
  6. Use built-in formatting methods (if they suit your needs) – JavaScript offers several convenience methods that output localized strings. toLocaleDateString() and toLocaleTimeString() let you specify options like weekday, year, month, day, hour, minute, second.
    console.log(now.toLocaleDateString('en-US', { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' }));
    // "Tuesday, April 15, 2025"
  7. Get UTC values – If you need to work with Coordinated Universal Time (UTC) regardless of the user's timezone, use the UTC variants of the getters: getUTCFullYear(), getUTCMonth(), getUTCDate(), etc.
    const utcHours = now.getUTCHours();

Common Mistakes

  • Forgetting that months are zero-indexed – getMonth() returns 0 for January, so you must add 1 to get the human-readable month number.
  • Using getYear() instead of getFullYear() – getYear() returns the year minus 1900, which is deprecated and confusing. Always use getFullYear().
  • Assuming Date is immutable – Many methods like setHours() mutate the original object. If you need to keep the original, create a copy first.
  • Ignoring timezone differences – toString() and the local getters use the system's timezone. If your app serves users in different timezones, you need to decide whether to use UTC or store timestamps and convert on the client.
  • Not padding single-digit values – Without padding, you get strings like "2025-4-5 9:5:3" instead of "2025-04-05 09:05:03", which can break sorting and display.

Tips

  • Use Date.now() for timestamps – It's slightly faster and cleaner than new Date().getTime() because it doesn't create an intermediate object.
  • Consider using Intl.DateTimeFormat for locale-aware formatting – It's more powerful than toLocaleString() and can format dates in any locale with correct plurals and order.
  • Store timestamps as numbers – For databases or APIs, use the numeric timestamp (milliseconds since epoch) to avoid timezone ambiguity. Convert to a readable string only when displaying.
  • For date-only comparisons, set the time to midnight – Use setHours(0,0,0,0) on a copy to compare just the date part.
  • Use a library for complex date manipulation – If you're doing a lot of timezone conversions, date arithmetic, or formatting, consider a well-tested library like date-fns or Luxon. For simple tasks, vanilla JS is fine.

Troubleshooting

  • My code returns the wrong date (one day off) – This usually happens when you create a Date object from a string like "2025-04-15". That string is interpreted as UTC midnight, which in a timezone behind UTC becomes the previous day. Always specify a time or use new Date(2025, 3, 15) (month is zero-indexed) to create a local date.
  • The time is off by a few hours – Check if you're mixing local and UTC methods. For example, using getHours() on a date that was created from a UTC string will show the local time, which might be different. Use the UTC getters consistently if you want UTC.
  • My formatted string has leading zeros missing – The pad() function in Step 4 is your friend. Make sure you apply it to hours, minutes, seconds, and day/month if you want consistent two-digit output.
  • I get NaN when I try to get the date – This usually means the Date object is invalid. For example, new Date('invalid') or new Date(undefined) will produce an invalid date. Check the value you passed to the constructor.
  • My code works in one browser but not another – Older browsers may not support certain methods like toLocaleDateString() with options. Use a polyfill or stick to basic getters for maximum compatibility.

Frequently Asked Questions

  1. What's the difference between Date.now() and new Date().getTime()?
    Both return the same numeric timestamp (milliseconds since January 1, 1970 UTC). Date.now() is a static method that doesn't require creating a Date object, so it's slightly faster and more concise.
  2. How do I get the current date in YYYY-MM-DD format?
    Use toISOString().slice(0,10) – but note that toISOString() returns UTC time, so it may be a different date than your local date. For local date, build it manually: const d = new Date(); const localDate = `${d.getFullYear()}-${String(d.getMonth()+1).padStart(2,'0')}-${String(d.getDate()).padStart(2,'0')}`;
  3. Why does new Date().getMonth() return 3 in April?
    Because months are zero-indexed: January is 0, February is 1, ..., December is 11. Always add 1 to get the familiar 1-12 numbering.
  4. How can I display the time in 12-hour format with AM/PM?
    Use toLocaleTimeString('en-US', { hour: 'numeric', minute: '2-digit', hour12: true }) – this will output something like "2:30 PM".
  5. Is it safe to compare dates using == or ===?
    No. Two Date objects are only equal if they reference the same object. To compare dates, compare their timestamps: date1.getTime() === date2.getTime() or use date1 - date2 === 0.
  6. How do I get the current time in UTC?
    Use new Date().toUTCString() for a readable string, or get individual UTC components like getUTCHours(), getUTCMinutes(), etc.