JavaScript Date & Time
Working with dates and times is essential for many applications. JavaScript provides the Date object for handling dates, times, and time zones.
📅 What are Dates in JavaScript?
JavaScript Date objects represent a single moment in time in a platform-independent format. Dates are stored as the number of milliseconds since January 1, 1970, UTC (the Unix epoch).
Date Characteristics:
- Based on Unix timestamp (milliseconds since 1970)
- Handles dates from about 285,616 years before/after 1970
- Month indexing starts at 0 (January = 0)
- Day of week indexing starts at 0 (Sunday = 0)
- Timezone-aware (can work with local or UTC)
💡 Date Creation Methods
// Current date/time
new Date();
// Specific date
new Date(2024, 0, 15); // Jan 15, 2024
new Date("2024-01-15");
new Date("01/15/2024");
// From timestamp
new Date(1705300200000);
// Date.UTC() for UTC
Date.UTC(2024, 0, 15);Important Notes:
• Months are 0-indexed (0 = January, 11 = December)
• Days of week are 0-indexed (0 = Sunday, 6 = Saturday)
• Two-digit years less than 50 are treated as 2000s
• Date strings should be in ISO 8601 format for reliability
🔧 Creating and Formatting Dates
Explore different ways to create dates and format them as strings.
Creation
new Date() new Date(year, month, day) new Date(timestamp) new Date(dateString)
String Formats
toString() toDateString() toTimeString() toISOString()
Local Formats
toLocaleString() toLocaleDateString() toLocaleTimeString()
📊 Date Get Methods
Extract components from Date objects using get methods.
Date Components
getFullYear()- 4-digit yeargetMonth()- Month (0-11)getDate()- Day of month (1-31)getDay()- Day of week (0-6)
Time Components
getHours()- Hours (0-23)getMinutes()- MinutesgetSeconds()- SecondsgetMilliseconds()- Milliseconds
Timestamps
getTime()- Milliseconds since 1970getTimezoneOffset()- Timezone offset in minutesvalueOf()- Same as getTime()
⚙️ Date Set Methods
Modify Date objects using set methods.
📌 Important Notes:
- Set methods automatically adjust overflow (e.g., setDate(32) becomes next month)
- Month parameter is 0-indexed in setMonth()
- setTime() accepts milliseconds since 1970
- UTC set methods set values in UTC time
- Setting components returns the updated timestamp
🧮 Date Operations
Perform calculations and comparisons with dates.
Date Arithmetic:
- Dates can be subtracted to get milliseconds
- Add/subtract milliseconds to/from timestamps
- Use set methods for date arithmetic
- Consider timezone differences in calculations
Comparisons:
- Use
<,>,<=,>=for comparisons ==and===compare object references- Compare timestamps for equality
- Consider milliseconds in exact comparisons
✨ Date Formatting
Format dates for display in various formats.
🎯 Intl.DateTimeFormat (Modern Approach):
// Locale-aware formatting
let formatter = new Intl.DateTimeFormat('en-US', {
dateStyle: 'full',
timeStyle: 'long'
});
console.log(formatter.format(new Date()));
// Relative time formatting
let rtf = new Intl.RelativeTimeFormat('en', {
numeric: 'auto'
});
console.log(rtf.format(-1, 'day')); // "yesterday"🌐 Timezone Handling
Work with different timezones and handle timezone conversions.
⚠️ Timezone Pitfalls:
- JavaScript Date objects work in local timezone by default
- Daylight Saving Time (DST) transitions can cause issues
- Use UTC for storage and calculations
- Convert to local time only for display
- Consider using libraries like date-fns or Luxon for complex timezone handling
🎮 Date Practice Exercises
Implement the date manipulation functions below.
💪 Additional Challenges:
- Create a countdown timer function
- Implement a function to get the week number of a date
- Create a calendar generator for a given month/year
- Build a function to handle recurring events
- Implement timezone-aware scheduling
📋 Quick Reference
Common Get Methods:
getFullYear()/getMonth()/getDate()getHours()/getMinutes()/getSeconds()getTime()- TimestampgetDay()- Day of weekgetTimezoneOffset()- Timezone offset
Common Set Methods:
setFullYear()/setMonth()/setDate()setHours()/setMinutes()/setSeconds()setTime()- Set via timestampsetMilliseconds()