How to Get Current Date in JavaScript: Simple Guide
To get the current date in JavaScript, create a new
Date object using new Date(). This object holds the current date and time, which you can format or extract parts from as needed.Syntax
The basic syntax to get the current date is to create a new Date object with no arguments. This captures the exact current date and time when the code runs.
new Date(): Creates a new date object with the current date and time.
javascript
const currentDate = new Date();
Example
This example shows how to get the current date and print it in a readable string format using toDateString().
javascript
const currentDate = new Date(); console.log(currentDate.toDateString());
Output
Fri Jun 21 2024
Common Pitfalls
One common mistake is trying to call Date() without new, which returns a string instead of a Date object. Another is assuming the default string output is always readable or consistent across browsers.
Always use new Date() to get a Date object and use methods like toDateString() or toISOString() to format it.
javascript
/* Wrong way - returns string */ const wrongDate = Date(); console.log(typeof wrongDate); // "string" /* Right way - returns Date object */ const rightDate = new Date(); console.log(typeof rightDate); // "object"
Output
string
object
Quick Reference
| Method | Description | Example Output |
|---|---|---|
| new Date() | Creates current date and time object | Fri Jun 21 2024 14:30:00 GMT+0000 (Coordinated Universal Time) |
| toDateString() | Returns date as readable string | Fri Jun 21 2024 |
| toISOString() | Returns date in ISO format | 2024-06-21T14:30:00.000Z |
| getFullYear() | Gets the year (4 digits) | 2024 |
| getMonth() | Gets month (0-11, Jan=0) | 5 |
| getDate() | Gets day of the month (1-31) | 21 |
Key Takeaways
Use
new Date() to get the current date and time as a Date object.Avoid calling
Date() without new because it returns a string, not a Date object.Use methods like
toDateString() or toISOString() to format the date for display.Remember months start at 0 in JavaScript, so January is 0 and December is 11.
Extract parts of the date with methods like
getFullYear(), getMonth(), and getDate().