To get the current date and time in JavaScript, use the Date
object. Here’s how to retrieve and format it:
1. Basic Current Date/Time
const currentDate = new Date();
console.log(currentDate);
// Output: Tue Aug 24 2024 15:30:45 GMT+0200 (Central European Summer Time)
2. Get Specific Date Components
Extract parts of the date (month is 0-indexed):
const year = currentDate.getFullYear(); // 2024
const month = currentDate.getMonth() + 1; // 8 (August is month 8, not 7!)
const day = currentDate.getDate(); // 24
const hours = currentDate.getHours(); // 15
const minutes = currentDate.getMinutes(); // 30
3. Format as a String
ISO Format (YYYY-MM-DD)
const isoDate = currentDate.toISOString().split('T')[0]; // "2024-08-24"
Custom Format (MM/DD/YYYY)
const formattedDate =
`${(month).toString().padStart(2, '0')}/${day.toString().padStart(2, '0')}/${year}`;
// "08/24/2024"
Locale-Specific Format
const localeDate = currentDate.toLocaleDateString('en-US'); // "8/24/2024"
const euDate = currentDate.toLocaleDateString('de-DE'); // "24.8.2024"
4. UTC Date/Time
Get the date in UTC (Coordinated Universal Time):
const utcYear = currentDate.getUTCFullYear(); // 2024
const utcMonth = currentDate.getUTCMonth() + 1; // 8
const utcDay = currentDate.getUTCDate(); // 24
5. Timestamp (Milliseconds Since Epoch)
const timestamp = Date.now(); // 1724513445000 (useful for comparisons)
Key Notes
- Month Index: Months are 0-indexed (January = 0, December = 11). Add
+1
for display. - Zero-Padding: Use
.padStart(2, '0')
to format values like05
instead of5
. - Time Zones: Use
getUTC*()
methods for universal time ortoLocaleString()
for localization. - Date Libraries: For advanced formatting, consider libraries like:
date-fns
(lightweight)moment.js
(legacy, but feature-rich)
Full Example
const today = new Date();
console.log(`Today is ${today.toLocaleDateString('en-US', {
weekday: 'long',
year: 'numeric',
month: 'long',
day: 'numeric'
})}`);
// Output: "Today is Saturday, August 24, 2024"
Use these methods to handle dates in forms, logs, or dynamic UIs!