JavaScript Program to Display Current Date (4 Ways)
Displaying the current date is a fundamental requirement in many web applications. It is commonly used for displaying the date on websites, recording timestamps for user activities, logging events, or performing date-based calculations. Whether you need to track orders, schedule appointments, or analyze trends, accurate date representation is crucial. JavaScript provides several ways to get the current date in JavaScript, offering flexibility to display it in various formats and styles to suit different application needs.
This program tutorial covers multiple methods to get today's date in JavaScript efficiently and accurately.
Get Current Date in JavaScript Using the Date Object
The simplest way to get the current date in JavaScript is by using the Date object.
Code
const currentDate = new Date();
console.log('Current Date:', currentDate);
Output
Current Date: Sat Jan 20 2024 14:30:00 GMT+0000 (Coordinated Universal Time)
Explanation
-
The Date object retrieves the full date and time details.
-
It includes the day, month, year, and timezone information.
Formatting Current Date in JavaScript Using toLocaleDateString()
The toLocaleDateString() method provides a localized way to display the date.
Code
const currentDate = new Date();
console.log('Formatted Date:', currentDate.toLocaleDateString());
Output
Formatted Date: 1/20/2024
Explanation
-
toLocaleDateString() formats the date based on the user's locale settings.
-
It provides an easy way to display dates in a region-specific format.
Displaying Date with Custom Format in JavaScript
To customize the date format, manually extract different parts of the date.
Code
const currentDate = new Date();
const day = currentDate.getDate();
const month = currentDate.getMonth() + 1; // Months are zero-indexed
const year = currentDate.getFullYear();
console.log(`Custom Formatted Date: ${day}-${month}-${year}`);
Output
Custom Formatted Date: 20-1-2024
Explanation
-
The getDate(), getMonth(), and getFullYear() methods extract specific date components.
-
This approach allows full control over date presentation.
Getting Current Date and Time in JavaScript
For applications requiring both date and time, toLocaleString() can be used.
Code
const currentDateTime = new Date();
console.log('Current Date and Time:', currentDateTime.toLocaleString());
Output
Current Date and Time: 1/20/2024, 2:30:00 PM
Explanation
-
toLocaleString() includes both date and time information in a readable format.
-
It helps when displaying real-time data to users.
Concepts Used Above in Displaying Current Date
Date Object
-
Provides built-in methods to retrieve and manipulate date values.
Localization
-
toLocaleDateString() and toLocaleString() adapt the output to the user's local settings.
Date Formatting
-
Extracting specific parts of the date for custom formatting.