📅 Date and Time = JavaScript
Dates are tricky. JavaScript date handling helps you manage dates and times effectively.
📝 Date Operations
// Create Date
const now = new Date();
const specific = new Date(2024, 0, 15); // Jan 15, 2024
const fromString = new Date('2024-01-15T10:00:00');
// Format Date
const date = new Date();
date.toLocaleDateString(); // '1/15/2024'
date.toLocaleString(); // '1/15/2024, 10:00:00 AM'
date.toISOString(); // '2024-01-15T10:00:00.000Z'
// Get Date Components
const year = date.getFullYear();
const month = date.getMonth(); // 0-11
const day = date.getDate();
const hours = date.getHours();
const minutes = date.getMinutes();
// Date Arithmetic
const future = new Date(date);
future.setDate(future.getDate() + 7); // Add 7 days
future.setMonth(future.getMonth() + 1); // Add 1 month
future.setFullYear(future.getFullYear() + 1); // Add 1 year
// Compare Dates
const date1 = new Date('2024-01-15');
const date2 = new Date('2024-01-16');
date1 < date2; // true
🎯 Advanced Date Patterns
// Date Utilities
class DateUtils {
static format(date, format) {
const map = {
'YYYY': date.getFullYear(),
'MM': String(date.getMonth() + 1).padStart(2, '0'),
'DD': String(date.getDate()).padStart(2, '0'),
'HH': String(date.getHours()).padStart(2, '0'),
'mm': String(date.getMinutes()).padStart(2, '0'),
'ss': String(date.getSeconds()).padStart(2, '0')
};
return format.replace(/YYYY|MM|DD|HH|mm|ss/g, match => map[match]);
}
static addDays(date, days) {
const result = new Date(date);
result.setDate(result.getDate() + days);
return result;
}
static getTimeAgo(date) {
const diff = Date.now() - date.getTime();
const seconds = Math.floor(diff / 1000);
const minutes = Math.floor(seconds / 60);
const hours = Math.floor(minutes / 60);
const days = Math.floor(hours / 24);
if (days > 0) return `${days} days ago`;
if (hours > 0) return `${hours} hours ago`;
if (minutes > 0) return `${minutes} minutes ago`;
return 'Just now';
}
static isWeekend(date) {
const day = date.getDay();
return day === 0 || day === 6;
}
static getDaysInMonth(year, month) {
return new Date(year, month + 1, 0).getDate();
}
}
// Moment-like API (Lightweight)
class DateTime {
constructor(date) {
this.date = new Date(date);
}
format(format) {
return DateUtils.format(this.date, format);
}
addDays(days) {
return new DateTime(DateUtils.addDays(this.date, days));
}
fromNow() {
return DateUtils.getTimeAgo(this.date);
}
}
💡 Date Tips
- Use ISO format for storage
- Handle timezones carefully
- Use UTC for backend
- Format for display locally
- Use libraries for complex operations
Date handling in JavaScript can be tricky. These patterns make it manageable and consistent.
