π‘ Key Takeaways
β° Creating Dates: new Date() creates a date object from string, timestamp, or components.
β‘ Modify Dates: Use setFullYear(), setMonth(), etc., to change parts of a date.
π Timestamps & UTC: Date.now() gives milliseconds since 1970-01-01; use getUTC*() for UTC times.
π― Formatting: toLocaleDateString(), toISOString(), and toTimeString() make dates readable.
πΉ Creating Dates
- Create current date/time with
new Date() - Use timestamps (ms since Jan 1 1970)
- Build custom dates with year, month, day, etc.
const now = new Date(); // current
const fromMs = new Date(1697040000000);
const custom = new Date(2025, 9, 11, 15, 30);
π’ Accessing Date Components
- Use getters like
getFullYear(),getMonth(),getDate() getDay()returns weekday (0 = Sun)getHours(),getMinutes(),getSeconds()for time
const now = new Date();
console.log(now.getFullYear(), now.getMonth(), now.getDate());
console.log(now.getDay(), now.getHours(), now.getMinutes());
βοΈ Modifying Dates
- Use setters like
setFullYear(),setMonth(),setDate() - Change hours, minutes, or seconds directly
- Great for scheduling or adjustments
const date = new Date();
date.setFullYear(2026);
date.setMonth(0); // January
date.setDate(1);
date.setHours(12, 0, 0);
π Timestamps and UTC
Date.now()β current timestamp (ms)- Use
getUTC*()for universal time - Convert timestamps back to Date
const ts = Date.now();
const now = new Date(ts);
console.log(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate());
π Formatting Dates
toISOString()β standardized outputtoLocaleDateString()β userβs region format- Combine parts manually for custom strings
const now = new Date();
console.log(now.toISOString());
console.log(now.toLocaleString());
const custom = `${now.getFullYear()}-${now.getMonth()+1}-${now.getDate()}`;
π Date Math
- Add or subtract days with
setDate() - Subtract two dates to get difference in ms
- Convert milliseconds β days/hours easily
const today = new Date();
today.setDate(today.getDate() + 5);
const d1 = new Date("2025-10-11");
const d2 = new Date("2025-10-01");
const diffDays = (d1 - d2) / (1000 * 60 * 60 * 24);