JavaScript — Lesson 11
Date & Time
Working with dates, times, and formatting.
Date & Time
JavaScript's Date object handles dates and times. The Intl.DateTimeFormat API provides locale-aware formatting.
Creating Dates
// Current date and time
const now = new Date();
console.log(now);
// Specific date (month is 0-indexed)
const birthday = new Date(2000, 5, 15); // June 15
// From string
const date = new Date("2026-07-25");
Getting Date Parts
const now = new Date();
now.getFullYear(); // 2026
now.getMonth(); // 6 (July, 0-indexed)
now.getDate(); // 25 (day of month)
now.getDay(); // 0-6 (0=Sunday)
now.getHours(); // 14 (24-hour)
now.getMinutes(); // 30
now.getSeconds(); // 45
now.getTime(); // ms since Jan 1, 1970
Formatting Dates
const date = new Date();
date.toLocaleDateString("en-US"); // "7/25/2026"
date.toLocaleDateString("en-GB"); // "25/07/2026"
date.toLocaleTimeString("en-US"); // "2:30:45 PM"
date.toISOString(); // "2026-07-25T14:30:45.000Z"
Intl.DateTimeFormat
const date = new Date();
const fmt = new Intl.DateTimeFormat("en-US", {
year: "numeric",
month: "long",
day: "numeric",
weekday: "long"
});
console.log(fmt.format(date));
// "Saturday, July 25, 2026"
Timestamps & Diff
const d1 = new Date("2026-01-01");
const d2 = new Date("2026-12-31");
const diff = (d2 - d1) / (1000 * 60 * 60 * 24);
console.log(diff + " days"); // "364 days"
Tip: Always store dates as ISO strings or timestamps. For serious date work, consider libraries like date-fns or Luxon.
Practice what you learned in the Deoit Editor — a free, browser-based code editor.
Open Editor →