How to Get Current Date and Time in JavaScript
In this article
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
- Create a new Date object – The simplest way to get the current date and time is to instantiate the
Dateobject without any arguments. This automatically captures the current moment in your system's local timezone.const now = new Date(); - 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)" - 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-12const day = now.getDate();const hours = now.getHours();const minutes = now.getMinutes();const seconds = now.getSeconds(); - 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" - Get the timestamp (milliseconds since Unix epoch) – For calculations, comparisons, or storing in databases, the numeric timestamp is often more useful. Use
getTime()orDate.now().const timestamp = now.getTime();const timestampNow = Date.now(); - Use built-in formatting methods (if they suit your needs) – JavaScript offers several convenience methods that output localized strings.
toLocaleDateString()andtoLocaleTimeString()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" - 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 ofgetFullYear()–getYear()returns the year minus 1900, which is deprecated and confusing. Always usegetFullYear(). - Assuming
Dateis immutable – Many methods likesetHours()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 thannew Date().getTime()because it doesn't create an intermediate object. - Consider using
Intl.DateTimeFormatfor locale-aware formatting – It's more powerful thantoLocaleString()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 usenew 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
NaNwhen I try to get the date – This usually means the Date object is invalid. For example,new Date('invalid')ornew 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
- What's the difference between
Date.now()andnew 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. - How do I get the current date in YYYY-MM-DD format?
UsetoISOString().slice(0,10)– but note thattoISOString()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')}`; - 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. - How can I display the time in 12-hour format with AM/PM?
UsetoLocaleTimeString('en-US', { hour: 'numeric', minute: '2-digit', hour12: true })– this will output something like "2:30 PM". - 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 usedate1 - date2 === 0. - How do I get the current time in UTC?
Usenew Date().toUTCString()for a readable string, or get individual UTC components likegetUTCHours(),getUTCMinutes(), etc.