Esta página está disponible temporalmente en inglés. La traducción al español está en preparación.
Introduction
JavaScript provides the Date object for working with dates and timestamps. Understanding how to properly use timestamps in JavaScript is essential for web development, data processing, and time-based applications. This guide covers timestamp fundamentals, conversions, timezone handling, and best practices.
Understanding JavaScript Timestamps
Unix Timestamp in JavaScript
JavaScript uses Unix timestamps in milliseconds since January 1, 1970, 00:00:00 UTC (the Unix epoch):
TEXT1JavaScript Timestamp = Milliseconds since 1970-01-01 00:00:00 UTC 2 3Example: 1704624000000 4 = 1704624000 seconds since epoch 5 = January 8, 2024, 12:00:00 PM UTC
Important: JavaScript uses milliseconds while many other systems use seconds. Always verify units when converting.
Current Timestamp
JAVASCRIPT1// Current timestamp in milliseconds 2const nowMs = Date.now(); 3console.log(nowMs); // e.g., 1704624000000 4 5// Alternative method 6const nowMs2 = new Date().getTime(); 7console.log(nowMs2); // Same as Date.now() 8 9// Convert to seconds 10const nowSec = Math.floor(Date.now() / 1000); 11console.log(nowSec); // e.g., 1704624000
Creating Dates
Creating Date Objects
From Timestamp
JAVASCRIPT1// Create from milliseconds timestamp 2const dateFromMs = new Date(1704624000000); 3console.log(dateFromMs.toISOString()); // "2024-01-08T12:00:00.000Z" 4 5// Create from seconds timestamp (multiply by 1000) 6const dateFromSec = new Date(1704624000 * 1000); 7console.log(dateFromSec.toISOString()); // "2024-01-08T12:00:00.000Z"
From Date Components
JAVASCRIPT1// Create from year, month, day (months are 0-indexed!) 2const date1 = new Date(2024, 0, 8); // January 8, 2024 3console.log(date1.toISOString()); // "2024-01-08T00:00:00.000Z" 4 5// Create with time 6const date2 = new Date(2024, 0, 8, 14, 30, 0); 7console.log(date2.toISOString()); // "2024-01-08T14:30:00.000Z" 8 9// Create from string (ISO 8601 recommended) 10const date3 = new Date('2024-01-08T14:30:00.000Z'); 11console.log(date3.toISOString()); // "2024-01-08T14:30:00.000Z"
Common Mistake: JavaScript months are 0-indexed (0 = January, 11 = December)!
Current Date and Time
JAVASCRIPT1const now = new Date(); 2 3console.log(now.toISOString()); // "2024-01-08T12:34:56.789Z" 4console.log(now.toString()); // "Mon Jan 08 2024 07:34:56 GMT-0500" 5console.log(now.toDateString()); // "Mon Jan 08 2024" 6console.log(now.toTimeString()); // "07:34:56 GMT-0500" 7console.log(now.toLocaleString()); // "1/8/2024, 7:34:56 AM"
Getting Date Components
Extracting Date Parts
JAVASCRIPT1const date = new Date(2024, 0, 8, 14, 30, 45, 123); 2 3// Get components 4console.log(date.getFullYear()); // 2024 5console.log(date.getMonth()); // 0 (January - 0-indexed!) 6console.log(date.getDate()); // 8 (day of month) 7console.log(date.getHours()); // 14 (hour 0-23) 8console.log(date.getMinutes()); // 30 (minutes 0-59) 9console.log(date.getSeconds()); // 45 (seconds 0-59) 10console.log(date.getMilliseconds()); // 123 (milliseconds 0-999) 11 12// Get day of week (0 = Sunday, 6 = Saturday) 13console.log(date.getDay()); // 1 (Monday) 14 15// Get UTC components 16console.log(date.getUTCFullYear()); // 2024 17console.log(date.getUTCHours()); // 19 (if local is 14:30)
Relative Time Components
JAVASCRIPT1const date = new Date(2024, 0, 8); 2 3// Get timezone offset (in minutes) 4const offset = date.getTimezoneOffset(); 5console.log(offset); // e.g., -300 (UTC-5 = -5 * 60) 6 7// Get timestamp 8const timestamp = date.getTime(); 9console.log(timestamp); // e.g., 1704672000000 (milliseconds) 10 11// Get ISO 8601 string 12const isoString = date.toISOString(); 13console.log(isoString); // "2024-01-08T00:00:00.000Z"
Setting Date Components
Modifying Dates
JAVASCRIPT1const date = new Date(2024, 0, 8); 2 3// Set components (returns timestamp) 4date.setFullYear(2025); 5date.setMonth(11); // December 6date.setDate(25); 7date.setHours(18); 8date.setMinutes(30); 9date.setSeconds(45); 10date.setMilliseconds(0); 11 12console.log(date.toISOString()); // "2025-12-25T18:30:45.000Z" 13 14// Set UTC components 15date.setUTCFullYear(2025); 16date.setUTCHours(12);
Important: Set methods return the timestamp, not the Date object. Chain carefully:
JAVASCRIPT1// Correct: Use same date object 2const date = new Date(2024, 0, 8); 3date.setDate(15); 4date.setMonth(5); // June 15, 2024 5 6// WRONG: Creates new date, loses changes 7const date = new Date(2024, 0, 8); 8new Date(date).setDate(15); // Original date unchanged!
Date Arithmetic
Adding and Subtracting Time
JAVASCRIPT1const date = new Date(2024, 0, 8); 2 3// Add 7 days 4date.setDate(date.getDate() + 7); 5console.log(date.toISOString()); // "2024-01-15T00:00:00.000Z" 6 7// Add 3 hours (3600 * 1000 ms) 8date.setTime(date.getTime() + (3 * 3600 * 1000)); 9console.log(date.toISOString()); // "2024-01-15T03:00:00.000Z" 10 11// Subtract 1 month 12date.setMonth(date.getMonth() - 1); 13console.log(date.toISOString()); // "2023-12-15T03:00:00.000Z" 14 15// Add 1 year 16date.setFullYear(date.getFullYear() + 1); 17console.log(date.toISOString()); // "2024-12-15T03:00:00.000Z"
Best Practice: Use timestamp arithmetic for precision:
JAVASCRIPT1// Add 1 hour in milliseconds (60 * 60 * 1000) 2const oneHour = 60 * 60 * 1000; 3const newDate = new Date(date.getTime() + oneHour);
Time Differences
JAVASCRIPT1const date1 = new Date(2024, 0, 8); 2const date2 = new Date(2024, 0, 15); 3 4// Difference in milliseconds 5const diffMs = date2 - date1; 6console.log(diffMs); // 604800000 (7 days in ms) 7 8// Convert to seconds, minutes, hours, days 9const diffSec = Math.floor(diffMs / 1000); 10const diffMin = Math.floor(diffMs / (1000 * 60)); 11const diffHours = Math.floor(diffMs / (1000 * 60 * 60)); 12const diffDays = Math.floor(diffMs / (1000 * 60 * 60 * 24)); 13 14console.log(`${diffDays} days`); // "7 days" 15console.log(`${diffHours} hours`); // "168 hours"
Formatting Dates
Built-in Formatting
toLocaleString Family
JAVASCRIPT1const date = new Date(2024, 0, 8, 14, 30, 45); 2 3// Locale-specific formats 4console.log(date.toLocaleDateString()); // "1/8/2024" 5console.log(date.toLocaleTimeString()); // "2:30:45 PM" 6console.log(date.toLocaleString()); // "1/8/2024, 2:30:45 PM" 7 8// With locale options 9console.log(date.toLocaleDateString('en-US', { 10 weekday: 'long', 11 year: 'numeric', 12 month: 'long', 13 day: 'numeric' 14})); 15// "Monday, January 8, 2024" 16 17console.log(date.toLocaleDateString('zh-CN', { 18 year: 'numeric', 19 month: 'long', 20 day: 'numeric' 21})); 22// "2024年1月8日"
International Formats
JAVASCRIPT1const date = new Date(2024, 0, 8); 2 3// ISO 8601 (always UTC) 4console.log(date.toISOString()); // "2024-01-08T00:00:00.000Z" 5 6// UTC string 7console.log(date.toUTCString()); // "Sun, 07 Jan 2024 00:00:00 GMT" 8 9// Date string (local time) 10console.log(date.toString()); // "Mon Jan 08 2024 00:00:00 GMT-0500"
Best Practice: Always use
toISOString()for API calls and database storage to avoid timezone issues.
Custom Formatting
JAVASCRIPT1// Manual formatting (use Intl.DateTimeFormat for i18n) 2function formatDate(date) { 3 const year = date.getFullYear(); 4 const month = String(date.getMonth() + 1).padStart(2, '0'); 5 const day = String(date.getDate()).padStart(2, '0'); 6 const hours = String(date.getHours()).padStart(2, '0'); 7 const minutes = String(date.getMinutes()).padStart(2, '0'); 8 const seconds = String(date.getSeconds()).padStart(2, '0'); 9 10 return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`; 11} 12 13console.log(formatDate(new Date(2024, 0, 8, 14, 30, 45))); 14// "2024-01-08 14:30:45"
Recommendation: Use libraries like date-fns, luxon, or day.js for complex formatting instead of manual formatting.
Timezone Handling
Working with Timezones
Getting Timezone Info
JAVASCRIPT1const date = new Date(); 2 3// Get timezone offset (in minutes) 4const offset = date.getTimezoneOffset(); 5console.log(offset); // e.g., -300 (UTC-5) or 300 (UTC+5) 6 7// Convert offset to hours 8const offsetHours = offset / 60; 9console.log(offsetHours); // -5 or 5 10 11// Get timezone name (browser-specific) 12const timezone = Intl.DateTimeFormat().resolvedOptions().timeZone; 13console.log(timezone); // e.g., "America/New_York"
Converting Between Timezones
JAVASCRIPT1const date = new Date(2024, 0, 8, 14, 30, 0); 2 3// Convert to different timezone using toLocaleString 4const nyTime = date.toLocaleString('en-US', { 5 timeZone: 'America/New_York', 6 timeZoneName: 'short' 7}); 8console.log(nyTime); // "1/8/2024, 9:30:00 AM EST" 9 10const tokyoTime = date.toLocaleString('en-US', { 11 timeZone: 'Asia/Tokyo' 12}); 13console.log(tokyoTime); // "1/8/2024, 11:30:00 PM" 14 15// Extract time components in specific timezone 16const tokyoDate = new Date(date.toLocaleString('en-US', { 17 timeZone: 'Asia/Tokyo' 18})); 19console.log(tokyoDate.getHours()); // 23 (11 PM)
Best Practice: Always work with UTC internally and convert to local timezone only for display.
UTC vs Local Time
JAVASCRIPT1const date = new Date(2024, 0, 8, 14, 30, 0); 2 3// Local time methods 4console.log(date.getHours()); // Local hour (e.g., 14 for EST) 5console.log(date.getTime()); // Timestamp (same regardless of timezone) 6 7// UTC methods 8console.log(date.getUTCHours()); // UTC hour (e.g., 19 for EST) 9console.log(date.getUTCDate()); // UTC day of month
Parsing Dates
Parsing Date Strings
Using Date Constructor
JAVASCRIPT1// ISO 8601 (recommended) 2const isoDate = new Date('2024-01-08T14:30:00.000Z'); 3console.log(isoDate.toISOString()); // "2024-01-08T14:30:00.000Z" 4 5// Short date format (browser-dependent, avoid!) 6const shortDate = new Date('01/08/2024'); 7console.log(shortDate); // May be Jan 8 or Aug 8 depending on locale 8 9// RFC 2822 format 10const rfcDate = new Date('Mon, 08 Jan 2024 14:30:00 GMT'); 11console.log(rfcDate.toISOString()); // "2024-01-08T14:30:00.000Z"
Problem: Date parsing is inconsistent across browsers and locales.
Manual Parsing
JAVASCRIPT1// Parse ISO 8601 string manually 2function parseISOString(isoString) { 3 const date = new Date(isoString); 4 if (isNaN(date.getTime())) { 5 throw new Error('Invalid date string'); 6 } 7 return date; 8} 9 10// Parse custom format (YYYY-MM-DD) 11function parseCustomDate(dateString) { 12 const [year, month, day] = dateString.split('-').map(Number); 13 return new Date(year, month - 1, day); // months are 0-indexed 14} 15 16console.log(parseCustomDate('2024-01-08').toISOString()); 17// "2024-01-08T00:00:00.000Z"
Recommendation: Use libraries like date-fns/parse or luxon/DateTime.fromISO for reliable parsing.
Validating Dates
JAVASCRIPT1// Check if date is valid 2function isValidDate(date) { 3 return date instanceof Date && !isNaN(date.getTime()); 4} 5 6// Examples 7const validDate = new Date(2024, 0, 8); 8const invalidDate = new Date('invalid'); 9 10console.log(isValidDate(validDate)); // true 11console.log(isValidDate(invalidDate)); // false 12console.log(isNaN(invalidDate.getTime())); // true (NaN)
Common Pitfalls
Month Indexing
JAVASCRIPT1// Common mistake: Using 1-12 for months 2const date = new Date(2024, 12, 8); // January 2025! 3console.log(date.toISOString()); // "2025-01-08T00:00:00.000Z" 4 5// Correct: Use 0-11 for months 6const date = new Date(2024, 11, 8); // December 2024 7console.log(date.toISOString()); // "2024-12-08T00:00:00.000Z"
Timezone Confusion
JAVASCRIPT1const date = new Date(2024, 0, 8, 0, 0, 0); 2 3// These produce different values! 4console.log(date.getTime()); // 1704672000000 (same) 5console.log(date.toString()); // "Mon Jan 08 2024 00:00:00 GMT-0500" 6console.log(date.toISOString()); // "2024-01-08T05:00:00.000Z" 7 8// Midnight EST = 5:00 AM UTC
Problem: Creating dates without timezone info assumes local time.
String Parsing Inconsistencies
JAVASCRIPT1// Different browsers may parse differently 2const date1 = new Date('2024-01-08'); // Might be Jan 8 or Jan 1 3const date2 = new Date('2024/01/08'); // Might be parsed differently 4const date3 = new Date('01-08-2024'); // Very ambiguous! 5 6// Always use ISO 8601 7const date = new Date('2024-01-08T00:00:00Z'); 8console.log(date.toISOString()); // Consistent across all browsers
Math Overflow
JAVASCRIPT1const date = new Date(2024, 0, 31); 2 3// Add 2 months to Jan 31 4date.setMonth(date.getMonth() + 2); 5console.log(date.toISOString()); // "2024-03-31T00:00:00.000Z" ✓ 6 7// Add 1 month to Jan 31 (February doesn't have 31!) 8date.setMonth(date.getMonth() + 1); 9console.log(date.toISOString()); // "2024-03-02T00:00:00.000Z" ✓ 10 11// JavaScript auto-adjusts overflow
Benefit: JavaScript automatically handles date overflow (Feb 31 → Mar 2 or 3 depending on leap year).
Best Practices
Performance
Avoid Frequent Date Creation
JAVASCRIPT1// BAD: Create new Date in loop 2for (let i = 0; i < 1000; i++) { 3 const now = new Date(); 4 // ... operations 5} 6 7// GOOD: Create once, reuse 8const now = new Date(); 9const timestamp = now.getTime(); 10for (let i = 0; i < 1000; i++) { 11 // ... operations with timestamp 12}
Use Timestamp for Comparisons
JAVASCRIPT1const date1 = new Date(2024, 0, 8); 2const date2 = new Date(2024, 0, 15); 3 4// BAD: Compare Date objects (slow) 5if (date1 < date2) { } 6 7// GOOD: Compare timestamps (fast) 8if (date1.getTime() < date2.getTime()) { } 9 10// Even better: Use timestamps directly 11const ts1 = date1.getTime(); 12const ts2 = date2.getTime(); 13if (ts1 < ts2) { }
Cache Timezone Offset
JAVASCRIPT1// Cache timezone offset (doesn't change during runtime) 2const TZ_OFFSET = new Date().getTimezoneOffset() * 60 * 1000; 3 4// Use in conversions 5function toLocalTime(timestamp) { 6 return new Date(timestamp + TZ_OFFSET); 7} 8 9console.log(toLocalTime(Date.now()));
Data Integrity
JAVASCRIPT1// Validate before operations 2function safeDateOperation(callback) { 3 try { 4 const result = callback(); 5 if (isNaN(result.getTime())) { 6 throw new Error('Invalid date result'); 7 } 8 return result; 9 } catch (error) { 10 console.error('Date operation failed:', error); 11 return new Date(); // Return current time as fallback 12 } 13} 14 15// Usage 16const result = safeDateOperation(() => { 17 return new Date(invalidInput); 18});
Storage Best Practices
JAVASCRIPT1// Store as ISO 8601 string 2function serializeDate(date) { 3 return date.toISOString(); 4} 5 6// Deserialize from ISO 8601 7function deserializeDate(isoString) { 8 return new Date(isoString); 9} 10 11// Usage in JSON 12const data = { 13 timestamp: Date.now(), 14 isoDate: new Date().toISOString(), 15 userCreated: serializeDate(new Date()) 16}; 17 18// Parse from API 19const createdDate = deserializeDate(apiResponse.userCreated);
Common Operations
Utility Functions
Start/End of Day
JAVASCRIPT1function startOfDay(date) { 2 const d = new Date(date); 3 d.setHours(0, 0, 0, 0); 4 return d; 5} 6 7function endOfDay(date) { 8 const d = new Date(date); 9 d.setHours(23, 59, 59, 999); 10 return d; 11} 12 13console.log(startOfDay(new Date()).toISOString()); 14// "2024-01-08T00:00:00.000Z"
Start/End of Week
JAVASCRIPT1function startOfWeek(date) { 2 const d = new Date(date); 3 const day = d.getDay(); 4 const diff = d.getDate() - day + (day === 0 ? -6 : 1); 5 d.setDate(diff); 6 return startOfDay(d); 7} 8 9function endOfWeek(date) { 10 const d = startOfWeek(new Date(date)); 11 d.setDate(d.getDate() + 6); 12 return endOfDay(d); 13} 14 15console.log(startOfWeek(new Date(2024, 0, 8)).toISOString()); 16// "2024-01-01T00:00:00.000Z" (Monday)
Start/End of Month
JAVASCRIPT1function startOfMonth(date) { 2 return new Date(date.getFullYear(), date.getMonth(), 1); 3} 4 5function endOfMonth(date) { 6 return new Date(date.getFullYear(), date.getMonth() + 1, 0); 7} 8 9console.log(startOfMonth(new Date(2024, 0, 15)).toISOString()); 10// "2024-01-01T00:00:00.000Z" 11 12console.log(endOfMonth(new Date(2024, 0, 15)).toISOString()); 13// "2024-01-31T00:00:00.000Z"
Age Calculation
JAVASCRIPT1function calculateAge(birthDate) { 2 const today = new Date(); 3 const birth = new Date(birthDate); 4 5 let years = today.getFullYear() - birth.getFullYear(); 6 const monthDiff = today.getMonth() - birth.getMonth(); 7 8 if (monthDiff < 0 || (monthDiff === 0 && today.getDate() < birth.getDate())) { 9 years--; 10 } 11 12 return years; 13} 14 15console.log(calculateAge('1990-06-15')); 16// 33 (assuming current date is 2024-01-08)
Business Days Calculation
JAVASCRIPT1function addBusinessDays(startDate, days) { 2 const result = new Date(startDate); 3 let addedDays = 0; 4 5 while (addedDays < days) { 6 result.setDate(result.getDate() + 1); 7 const dayOfWeek = result.getDay(); 8 9 if (dayOfWeek !== 0 && dayOfWeek !== 6) { // Not weekend 10 addedDays++; 11 } 12 } 13 14 return result; 15} 16 17console.log(addBusinessDays(new Date(2024, 0, 8), 5).toISOString()); 18// "2024-01-15T00:00:00.000Z" (skips weekend)
Examples and Use Cases
Countdown Timer
JAVASCRIPT1function countdown(targetDate) { 2 const now = Date.now(); 3 const target = new Date(targetDate).getTime(); 4 const diff = target - now; 5 6 if (diff <= 0) { 7 return { expired: true }; 8 } 9 10 const days = Math.floor(diff / (1000 * 60 * 60 * 24)); 11 const hours = Math.floor((diff % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60)); 12 const minutes = Math.floor((diff % (1000 * 60 * 60)) / (1000 * 60)); 13 const seconds = Math.floor((diff % (1000 * 60)) / 1000); 14 15 return { 16 expired: false, 17 days, 18 hours, 19 minutes, 20 seconds, 21 totalMs: diff 22 }; 23} 24 25console.log(countdown('2024-12-31')); 26// { expired: false, days: 357, hours: 11, minutes: 29, seconds: 12, totalMs: ... }
Relative Time (e.g., "2 hours ago")
JAVASCRIPT1function timeAgo(timestamp) { 2 const now = Date.now(); 3 const diff = now - timestamp; 4 const seconds = Math.floor(diff / 1000); 5 6 if (seconds < 60) return 'just now'; 7 const minutes = Math.floor(seconds / 60); 8 if (minutes < 60) return `${minutes} minute${minutes !== 1 ? 's' : ''} ago`; 9 const hours = Math.floor(minutes / 60); 10 if (hours < 24) return `${hours} hour${hours !== 1 ? 's' : ''} ago`; 11 const days = Math.floor(hours / 24); 12 if (days < 30) return `${days} day${days !== 1 ? 's' : ''} ago`; 13 const months = Math.floor(days / 30); 14 if (months < 12) return `${months} month${months !== 1 ? 's' : ''} ago`; 15 const years = Math.floor(days / 365); 16 return `${years} year${years !== 1 ? 's' : ''} ago`; 17} 18 19const oneHourAgo = Date.now() - (60 * 60 * 1000); 20console.log(timeAgo(oneHourAgo)); // "1 hour ago"
Date Range Validation
JAVASCRIPT1function isDateInRange(date, startDate, endDate) { 2 const timestamp = date.getTime(); 3 return timestamp >= startDate.getTime() && timestamp <= endDate.getTime(); 4} 5 6// Example: Check if date is in Q1 2024 7const q1Start = new Date(2024, 0, 1); 8const q1End = new Date(2024, 2, 31); 9const testDate = new Date(2024, 1, 15); 10 11console.log(isDateInRange(testDate, q1Start, q1End)); // true 12console.log(isDateInRange(new Date(2024, 3, 1), q1Start, q1End)); // false
Best Practices Summary
JavaScript Date Checklist
TEXT1✅ Always use ISO 8601 format ('2024-01-08T14:30:00.000Z') for strings 2✅ Work with timestamps internally, convert to Date only for display 3✅ Use toISOString() for API calls and database storage 4✅ Remember months are 0-indexed (0 = January, 11 = December) 5✅ Cache timezone offset and Date.now() to avoid repeated calls 6✅ Validate dates with isNaN(date.getTime()) 7✅ Use Intl.DateTimeFormat for i18n-aware formatting 8✅ Consider libraries (date-fns, luxon, day.js) for complex operations 9✅ Use timestamp arithmetic for precision (add/subtract milliseconds) 10✅ Handle date overflow gracefully (JavaScript auto-adjusts) 11❌ Don't use locale-specific strings for parsing (inconsistent across browsers) 12❌ Don't mix UTC and local methods in same calculation 13❌ Don't create Date objects in loops (reuse or use timestamps) 14❌ Don't assume browser timezones (always validate with getTimezoneOffset) 15❌ Don't rely on automatic string parsing (use ISO 8601) 16❌ Don't forget about DST transitions when calculating business days
Performance Tips
TEXT1✅ Cache Date.now() instead of calling repeatedly 2✅ Use timestamps for comparisons (faster than Date objects) 3✅ Minimize Date object creation in loops 4✅ Use Math.floor() instead of bitwise operators for readability 5✅ Store timezone offset as constant for repeated calculations 6❌ Don't use Date.parse() on non-ISO strings (unreliable) 7❌ Don't create Date objects in hot code paths 8❌ Don't use toLocaleString() in performance-critical sections
Related Tools
- Unix Timestamp Converter - Convert Unix timestamps to dates
- Current Timestamp - Get current timestamp in multiple formats
- Timestamp Format Converter - Convert between timestamp formats
- JavaScript Timestamp Helper - JavaScript-specific examples
- UTC/Local Converter - Convert between UTC and local time
Additional Resources
For production applications with complex date/time requirements, consider using libraries like:
- date-fns: Modular, immutable date utilities
- luxon: Modern API with timezone support (from Moment.js creators)
- day.js: Lightweight alternative to Moment.js (2KB)
- temporal-polyfill: Future TC39 Temporal API proposal
Native Date is sufficient for basic operations, but libraries provide better ergonomics and timezone handling for complex use cases.