Date and Time Handling
Working with dates and times in JavaScript
Challenge
Section titled “Challenge”Handle timezone conversions, format dates correctly, and manage recurring events or scheduling.
Explanation
Section titled “Explanation”The Date object represents a single moment in time, though it has limitations. Modern development often uses libraries, but understanding Date is fundamental.
Creating Dates
Section titled “Creating Dates”// Current date/timeconst now = new Date();
// Specific dateconst date1 = new Date('2024-01-15');const date2 = new Date('2024-01-15T10:30:00');const date3 = new Date(2024, 0, 15); // Month is 0-indexed
// Unix timestamp (milliseconds since 1970-01-01)const date4 = new Date(1705316400000);const timestamp = Date.now(); // Current timestampGetting Date Components
Section titled “Getting Date Components”const date = new Date('2024-01-15T14:30:45');
console.log(date.getFullYear()); // 2024console.log(date.getMonth()); // 0 (January, 0-indexed)console.log(date.getDate()); // 15console.log(date.getDay()); // 1 (Monday, 0 = Sunday)console.log(date.getHours()); // 14console.log(date.getMinutes()); // 30console.log(date.getSeconds()); // 45console.log(date.getTime()); // Timestamp in msFormatting Dates
Section titled “Formatting Dates”// ISO stringconst isoString = new Date().toISOString();console.log(isoString); // '2024-01-15T14:30:45.000Z'
// Locale stringconst dateString = new Date().toLocaleDateString('en-US');console.log(dateString); // '1/15/2024'
// Custom formattingfunction formatDate(date) { const year = date.getFullYear(); const month = String(date.getMonth() + 1).padStart(2, '0'); const day = String(date.getDate()).padStart(2, '0'); return `${year}-${month}-${day}`;}
console.log(formatDate(new Date())); // '2024-01-15'Date Calculations
Section titled “Date Calculations”const date = new Date();
// Add daysconst nextWeek = new Date(date.getTime() + 7 * 24 * 60 * 60 * 1000);
// Difference between datesconst start = new Date('2024-01-01');const end = new Date('2024-01-15');const diffMs = end - start;const diffDays = Math.floor(diffMs / (1000 * 60 * 60 * 24));console.log(diffDays); // 14
// Check if pastfunction isPast(date) { return date.getTime() < Date.now();}
// Check if todayfunction isToday(date) { const today = new Date(); return date.toDateString() === today.toDateString();}Timezone Handling
Section titled “Timezone Handling”// UTC vs Localconst date = new Date();console.log(date.toISOString()); // UTCconsole.log(date.toLocaleString()); // Local timezone
// Get timezone offsetconst offset = new Date().getTimezoneOffset(); // Minutesconsole.log(offset / 60); // Hours
// Convert to specific timezone (simplified)function getTimeInTimezone(date, timeZone) { return new Intl.DateTimeFormat('en-US', { timeZone, year: 'numeric', month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit', second: '2-digit' }).format(date);}
console.log(getTimeInTimezone(new Date(), 'America/New_York'));Limitations and Best Practices
Section titled “Limitations and Best Practices”// ❌ Problems with Datenew Date('2024-01-15'); // Parses as UTC but returns local timenew Date(2024, 0, 15); // Month is 0-indexed (confusing!)
// ✅ Best practices// 1. Use ISO 8601 format for storage/transmissionconst iso = new Date().toISOString();
// 2. Use libraries for complex operations// npm install date-fns// npm install dayjs
// 3. Always consider timezoneconst utcDate = new Date('2024-01-15T10:30:00Z');const localDate = new Date('2024-01-15T10:30:00');