Working with date and time is a crucial part of any modern web application. Whether you're building a to-do list, a weather app, or a calendar, JavaScript provides powerful tools to manage dates and times. In this article, we'll explore the Date object in JavaScript, common methods, formatting techniques, and practical examples to make your learning easier.
---
title: "📅 Understanding Date and Time in JavaScript"
tags: [javascript, webdev, beginners, programming, date]
cover_image: https://res.cloudinary.com/practicaldev/image/fetch/s--M65ICat8--/c_imagga_scale,f_auto,fl_progressive,h_420,q_auto,w_1000/https://images.unsplash.com/photo-1521208919505-15097b20c5fe
---
# 📅 Understanding Date and Time in JavaScript
## 🕒 The `Date` Object in JavaScript
```
javascript
const currentDate = new Date();
console.log(currentDate);
📌 Creating Date Objects
Current Date and Time
javascript
const now = new Date();
Specific Date and Time
javascript
const specificDate = new Date(2025, 4, 4, 10, 30, 0); // May 4, 2025, 10:30:00
From a Date String
javascript
const fromString = new Date("2025-05-04T10:30:00");
🛠 Common Date Methods
javascript
const date = new Date();
console.log("Year:", date.getFullYear());
console.log("Month:", date.getMonth() + 1); // Add 1 for correct month
console.log("Day:", date.getDate());
console.log("Weekday:", date.getDay());
console.log("Hours:", date.getHours());
console.log("Minutes:", date.getMinutes());
console.log("Seconds:", date.getSeconds());
console.log("Milliseconds:", date.getMilliseconds());
🧮 Setting Date Values
javascript
let date = new Date();
date.setFullYear(2026);
date.setMonth(11); // December
date.setDate(25);
console.log(date); // 2026-12-25
⏰ Working with Timestamps
javascript
const now = Date.now();
console.log("Current timestamp:", now);
javascript
const timestamp = new Date().getTime();
🔄 Formatting Date and Time
Custom Format
javascript
const date = new Date();
const formatted = `${date.getDate()}/${date.getMonth() + 1}/${date.getFullYear()}`;
console.log("Formatted:", formatted);
Localized Format
javascript
const date = new Date();
console.log(date.toLocaleDateString()); // e.g., 5/4/2025
console.log(date.toLocaleTimeString()); // e.g., 10:45:00 AM
🧪 Comparing Dates
javascript
const date1 = new Date("2025-05-04");
const date2 = new Date("2025-06-04");
if (date1 < date2) {
console.log("date1 is earlier");
}
⚡ Using date-fns for Formatting
javascript
import { format } from 'date-fns';
const result = format(new Date(), 'dd/MM/yyyy');
console.log(result); // e.g., 04/05/2025
✅ Try It Yourself!
Want a fun challenge? Try building a Digital Clock or a Countdown Timer using setInterval()
and the Date
object! 🧠💡