Date and Time
JavaScript Date object provides methods to work with dates and times, from creation to formatting and manipulation.
Creating Date Objects
javascript// Current date and time const now = new Date(); console.log(now); // Current date and time // Timestamp (milliseconds since Jan 1, 1970) const timestamp = Date.now(); console.log(timestamp); // e.g., 1705312200000 // From timestamp const dateFromTimestamp = new Date(timestamp); console.log(dateFromTimestamp); // Specific dates const date1 = new Date(2024, 0, 15); // January 15, 2024 (month is 0-indexed) const date2 = new Date(2024, 0, 15, 14, 30, 0); // January 15, 2024, 2:30 PM // From date strings const date3 = new Date('2024-01-15'); const date4 = new Date('January 15, 2024'); const date5 = new Date('2024-01-15T14:30:00'); console.log(date1); // Mon Jan 15 2024 console.log(date2); // Mon Jan 15 2024 14:30:00
Getting Date Components
javascriptconst date = new Date('2024-01-15T14:30:45'); // Date parts console.log(date.getFullYear()); // 2024 console.log(date.getMonth()); // 0 (January, 0-indexed) console.log(date.getDate()); // 15 (day of month) console.log(date.getDay()); // 1 (Monday, 0=Sunday) // Time parts console.log(date.getHours()); // 14 console.log(date.getMinutes()); // 30 console.log(date.getSeconds()); // 45 console.log(date.getMilliseconds()); // 0 // UTC versions console.log(date.getUTCFullYear()); // 2024 console.log(date.getUTCMonth()); // 0 console.log(date.getUTCHours()); // May differ based on timezone
Setting Date Components
javascriptconst date = new Date(); // Set date parts date.setFullYear(2025); date.setMonth(11); // December (0-indexed) date.setDate(25); // Christmas Day // Set time parts date.setHours(12); date.setMinutes(0); date.setSeconds(0); date.setMilliseconds(0); console.log(date); // December 25, 2025 at noon // Chaining is possible const newYear = new Date() .setFullYear(2025, 0, 1); // January 1, 2025
Date Formatting
javascriptconst date = new Date('2024-01-15T14:30:00'); // Built-in formatting methods console.log(date.toString()); // "Mon Jan 15 2024 14:30:00 GMT-0500 (EST)" console.log(date.toDateString()); // "Mon Jan 15 2024" console.log(date.toTimeString()); // "14:30:00 GMT-0500 (EST)" console.log(date.toISOString()); // "2024-01-15T19:30:00.000Z" // Locale-specific formatting console.log(date.toLocaleDateString()); // "1/15/2024" (US format) console.log(date.toLocaleTimeString()); // "2:30:00 PM" console.log(date.toLocaleString()); // "1/15/2024, 2:30:00 PM" // Custom locale formatting console.log(date.toLocaleDateString('en-GB')); // "15/01/2024" (UK format) console.log(date.toLocaleDateString('de-DE')); // "15.1.2024" (German format) // Advanced formatting options const options = { year: 'numeric', month: 'long', day: 'numeric', weekday: 'long' }; console.log(date.toLocaleDateString('en-US', options)); // "Monday, January 15, 2024"
Custom Date Formatting
javascriptfunction formatDate(date, format = 'YYYY-MM-DD') { const year = date.getFullYear(); const month = String(date.getMonth() + 1).padStart(2, '0'); const day = String(date.getDate()).padStart(2, '0'); const hours = String(date.getHours()).padStart(2, '0'); const minutes = String(date.getMinutes()).padStart(2, '0'); const seconds = String(date.getSeconds()).padStart(2, '0'); const formats = { 'YYYY-MM-DD': `${year}-${month}-${day}`, 'DD/MM/YYYY': `${day}/${month}/${year}`, 'MM/DD/YYYY': `${month}/${day}/${year}`, 'YYYY-MM-DD HH:mm': `${year}-${month}-${day} ${hours}:${minutes}`, 'DD MMM YYYY': `${day} ${getMonthName(date.getMonth())} ${year}` }; return formats[format] || formats['YYYY-MM-DD']; } function getMonthName(monthIndex) { const months = [ 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec' ]; return months[monthIndex]; } const date = new Date(); console.log(formatDate(date, 'YYYY-MM-DD')); // "2024-01-15" console.log(formatDate(date, 'DD/MM/YYYY')); // "15/01/2024" console.log(formatDate(date, 'DD MMM YYYY')); // "15 Jan 2024"
Date Calculations
javascriptconst today = new Date(); // Add/subtract days const tomorrow = new Date(today); tomorrow.setDate(today.getDate() + 1); const yesterday = new Date(today); yesterday.setDate(today.getDate() - 1); const nextWeek = new Date(today); nextWeek.setDate(today.getDate() + 7); // Add/subtract months const nextMonth = new Date(today); nextMonth.setMonth(today.getMonth() + 1); const lastMonth = new Date(today); lastMonth.setMonth(today.getMonth() - 1); // Add/subtract years const nextYear = new Date(today); nextYear.setFullYear(today.getFullYear() + 1); console.log('Today:', formatDate(today)); console.log('Tomorrow:', formatDate(tomorrow)); console.log('Next week:', formatDate(nextWeek));
Time Differences
javascriptconst start = new Date('2024-01-01T00:00:00'); const end = new Date('2024-01-15T12:30:00'); // Difference in milliseconds const diffMs = end - start; console.log('Difference in ms:', diffMs); // Convert to different units const diffSeconds = Math.floor(diffMs / 1000); const diffMinutes = Math.floor(diffMs / (1000 * 60)); const diffHours = Math.floor(diffMs / (1000 * 60 * 60)); const diffDays = Math.floor(diffMs / (1000 * 60 * 60 * 24)); console.log('Difference:', diffDays, 'days'); console.log('Difference:', diffHours, 'hours'); // Age calculation function calculateAge(birthDate) { const today = new Date(); const birth = new Date(birthDate); let age = today.getFullYear() - birth.getFullYear(); // Adjust if birthday hasn't occurred this year const monthDiff = today.getMonth() - birth.getMonth(); if (monthDiff < 0 || (monthDiff === 0 && today.getDate() < birth.getDate())) { age--; } return age; } console.log('Age:', calculateAge('1990-05-15')); // Age in years // Time until/since function timeUntil(targetDate) { const now = new Date(); const target = new Date(targetDate); const diff = target - now; if (diff < 0) { return 'Date has passed'; } const days = Math.floor(diff / (1000 * 60 * 60 * 24)); const hours = Math.floor((diff % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60)); const minutes = Math.floor((diff % (1000 * 60 * 60)) / (1000 * 60)); return `${days} days, ${hours} hours, ${minutes} minutes`; } console.log('Time until New Year:', timeUntil('2025-01-01T00:00:00'));
Practical Examples
javascript// Date validation function isValidDate(dateString) { const date = new Date(dateString); return date instanceof Date && !isNaN(date); } console.log(isValidDate('2024-01-15')); // true console.log(isValidDate('invalid-date')); // false // Business days calculation function addBusinessDays(date, days) { const result = new Date(date); let addedDays = 0; while (addedDays < days) { result.setDate(result.getDate() + 1); // Skip weekends (0 = Sunday, 6 = Saturday) if (result.getDay() !== 0 && result.getDay() !== 6) { addedDays++; } } return result; } const startDate = new Date('2024-01-15'); // Monday const businessDate = addBusinessDays(startDate, 5); console.log('5 business days later:', formatDate(businessDate)); // Countdown timer function createCountdown(targetDate) { const target = new Date(targetDate); function update() { const now = new Date(); const diff = target - now; if (diff <= 0) { return 'Time's up!'; } const days = Math.floor(diff / (1000 * 60 * 60 * 24)); const hours = Math.floor((diff % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60)); const minutes = Math.floor((diff % (1000 * 60 * 60)) / (1000 * 60)); const seconds = Math.floor((diff % (1000 * 60)) / 1000); return `${days}d ${hours}h ${minutes}m ${seconds}s`; } return update; } const countdown = createCountdown('2024-12-31T23:59:59'); console.log(countdown()); // e.g., "350d 9h 29m 59s" // Date range checker function isDateInRange(date, startDate, endDate) { const checkDate = new Date(date); const start = new Date(startDate); const end = new Date(endDate); return checkDate >= start && checkDate <= end; } console.log(isDateInRange('2024-06-15', '2024-01-01', '2024-12-31')); // true // Get date range function getDateRange(startDate, endDate) { const dates = []; const current = new Date(startDate); const end = new Date(endDate); while (current <= end) { dates.push(new Date(current)); current.setDate(current.getDate() + 1); } return dates; } const range = getDateRange('2024-01-01', '2024-01-07'); console.log('Date range:', range.map(d => formatDate(d)));