JavaScript Date & Time: In-Depth Guide
📅 Introduction
Mastering date and time in JavaScript is essential for handling user input, timestamps, scheduling, logging, and more. This guide covers native JavaScript Date object, formatting, manipulation, parsing, and popular libraries.
⚡ Creating Dates
// Current date/timeconst now = new Date();
// Specific date (YYYY-MM-DDTHH:MM:SSZ)const date1 = new Date("2025-07-26T13:00:00Z");
// Year, month (0-indexed), day, hour, minute, secondconst date2 = new Date(2025, 6, 26, 13, 0, 0);
// From timestampconst timestamp = Date.now(); // ms since 1970const date3 = new Date(timestamp);🔄 Date Components (Get/Set)
const d = new Date();
// Gettersd.getFullYear(); // 2025d.getMonth(); // 0-11d.getDate(); // 1-31d.getDay(); // 0 (Sun) to 6 (Sat)d.getHours(), d.getMinutes(), d.getSeconds();d.getTime(); // timestamp in ms
// Settersd.setFullYear(2030);d.setMonth(11);d.setDate(31);d.setHours(23, 59, 59);📝 Date Formats
new Date().toString(); // Full local stringnew Date().toISOString(); // ISO formatnew Date().toUTCString(); // UTC timenew Date().toDateString(); // "Sat Jul 26 2025"new Date().toLocaleDateString(); // Based on locale📥 Parsing Dates
Date.parse("2025-07-26"); // returns timestampnew Date("July 26, 2025 13:00"); // OKnew Date("07/26/2025"); // may vary by browser (avoid this!)✅ Best Practice: Prefer ISO format (YYYY-MM-DD)
⚖️ Date Math (Add/Subtract)
const now = new Date();
// Add 5 daysconst future = new Date(now);future.setDate(now.getDate() + 5);
// Subtract 2 hoursconst past = new Date(now);past.setHours(now.getHours() - 2);
// Milliseconds differenceconst diff = future - now; // in msconst diffDays = diff / (1000 * 60 * 60 * 24);🔍 Comparing Dates
const a = new Date("2025-01-01");const b = new Date("2025-12-31");
console.log(a < b); // trueconsole.log(a.getTime() === b.getTime()); // false🌍 Working with Timezones
JavaScript Date objects are timezone-aware (local time) but store internally in UTC.
new Date().getTimezoneOffset(); // Difference in minutes from UTCUse toLocaleString() for timezone conversions:
new Date().toLocaleString("en-US", { timeZone: "Asia/Kolkata" });📋 Date Formatting Options
const now = new Date();now.toLocaleDateString("en-US", { weekday: "long", year: "numeric", month: "long", day: "numeric",});🌐 Internationalization (Intl)
Use Intl.DateTimeFormat for powerful formatting:
const formatter = new Intl.DateTimeFormat("en-GB", { dateStyle: "full", timeStyle: "short",});formatter.format(new Date());🛠️ Using Libraries
1. date-fns
npm install date-fnsimport { format, addDays, parseISO } from "date-fns";
format(new Date(), "yyyy-MM-dd"); // 2025-07-26addDays(new Date(), 5);2. dayjs
npm install dayjsimport dayjs from "dayjs";
dayjs().add(1, 'week').format("YYYY-MM-DD");3. luxon (for timezone and locale handling)
import { DateTime } from "luxon";
DateTime.now().setZone("Asia/Kolkata").toLocaleString(DateTime.DATETIME_MED);⚠️ Common Pitfalls
Monthis 0-indexed (January is 0)Date.parse()can behave inconsistently across browsers- Avoid relying on locale-specific formats (
MM/DD/YYYY) - Timezone differences can cause unexpected date shifts
✅ Best Practices
- Use ISO format for storage and comparison
- Use
toLocaleString()orIntl.DateTimeFormatfor UI - Prefer libraries like
date-fnsordayjsfor manipulation - Convert all times to UTC for consistent backend storage
- Validate user input dates properly before parsing
📚 Resources
💻 Example Playground
const event = new Date("2025-12-31T23:59:59");console.log("Event Date:", event.toLocaleString("en-IN", { timeZone: "Asia/Kolkata" }));Tip: When in doubt, always log
date.toISOString()to debug what the actual UTC time is.