JavaScript Tutorial in Hindi #21 | Date & Time Methods (2025)
✅ 1. Create a Date Object
You can create a date object in several ways:
js
CopyEdit
let now = new Date(); // Current date and time
let birthday = new Date("2000-12-25"); // Specific date
let customDate = new Date(2025, 4, 20); // (Year, Month[0-11], Day)
✅ 2. Get Date & Time Parts
You can extract parts of a date using built-in methods:
js
CopyEdit
let date = new Date();
console.log(date.getFullYear()); // 2025
console.log(date.getMonth()); // 4 (May, months start at 0)
console.log(date.getDate()); // 20
console.log(date.getDay()); // 2 (0 = Sunday)
console.log(date.getHours()); // current hour
console.log(date.getMinutes()); // current minute
console.log(date.getSeconds()); // current second
✅ 3. Set or Modify Date
You can change parts of a date object:
js
CopyEdit
let d = new Date();
d.setFullYear(2030);
d.setMonth(0); // January
d.setDate(15);
console.log(d); // Modified date object
✅ 4. Format Date into String
Some quick ways to get readable formats:
js
CopyEdit
let today = new Date();
console.log(today.toDateString()); // "Tue May 20 2025"
console.log(today.toTimeString()); // "17:35:24 GMT+..."
console.log(today.toLocaleString()); // "5/20/2025, 5:35:24 PM"
For custom formats, use:
js
CopyEdit
let d = new Date();
let formatted = `${d.getDate()}/${d.getMonth() + 1}/${d.getFullYear()}`;
console.log(formatted); // "20/5/2025"
✅ 5. Get Current Timestamp & Date Difference
🔹 Current Timestamp:
js
CopyEdit
let timestamp = Date.now(); // milliseconds since Jan 1, 1970
console.log(timestamp);
🔹 Date Difference (in days):
js
CopyEdit
let start = new Date("2025-01-01");
let end = new Date("2025-05-20");
let diffTime = end - start; // milliseconds
let diffDays = diffTime / (1000 * 60 * 60 * 24);
console.log(diffDays); // 139 days