Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How do I get the current date in JavaScript?
To get the current date in JavaScript, you can use the Date object along with various methods to extract different parts of the date.
Getting the Current Date Object
The new Date() constructor creates a Date object representing the current date and time:
var currentDate = new Date(); console.log(currentDate);
2024-01-15T10:30:45.123Z
Getting the Day of the Month
The getDate() method returns the day of the month (1-31):
var date = new Date();
var dayOfMonth = date.getDate();
console.log("Day of month: " + dayOfMonth);
Day of month: 15
Complete Date Information
You can extract different parts of the date using various methods:
var date = new Date();
console.log("Full year: " + date.getFullYear());
console.log("Month (0-11): " + date.getMonth());
console.log("Day of month: " + date.getDate());
console.log("Day of week (0-6): " + date.getDay());
Full year: 2024 Month (0-11): 0 Day of month: 15 Day of week: 1
Formatted Date Strings
For displaying dates in a readable format, you can use built-in methods:
var date = new Date();
console.log("Date string: " + date.toDateString());
console.log("Locale date: " + date.toLocaleDateString());
console.log("ISO string: " + date.toISOString().split('T')[0]);
Date string: Mon Jan 15 2024 Locale date: 1/15/2024 ISO string: 2024-01-15
Interactive Example
Here's a complete example that displays the current date when a button is clicked:
function displayCurrentDate() {
var date = new Date();
var day = date.getDate();
var month = date.getMonth() + 1; // Add 1 because months are 0-indexed
var year = date.getFullYear();
var formattedDate = month + "/" + day + "/" + year;
document.getElementById("dateResult").innerHTML = "Today's date: " + formattedDate;
}
Date Methods Summary
| Method | Returns | Range |
|---|---|---|
getDate() |
Day of month | 1-31 |
getMonth() |
Month | 0-11 (0=January) |
getFullYear() |
Four-digit year | e.g., 2024 |
getDay() |
Day of week | 0-6 (0=Sunday) |
Conclusion
Use new Date() to get the current date object, then apply methods like getDate(), getMonth(), and getFullYear() to extract specific date components. Remember that months are zero-indexed in JavaScript.
