-
-
Notifications
You must be signed in to change notification settings - Fork 2
JavaScript Date Time
Mattscreative edited this page Feb 21, 2026
·
1 revision
- Introduction
- Creating Dates
- Getting Date Components
- Setting Date Components
- Date Formatting
- Date Arithmetic
- Date Comparison
- Time Zones
- Practical Examples
- Libraries
JavaScript's Date object handles dates and times. It represents a single moment in time across different time zones.
// Current date and time
const now = new Date();
console.log(now); // Current date/time
// From timestamp (milliseconds since Jan 1, 1970)
const fromTimestamp = new Date(1704067200000);
console.log(fromTimestamp);
// From date string
const fromString = new Date("2024-01-01T00:00:00Z");
console.log(fromString);
// From individual components (year, monthIndex, day, hour, minute, second, ms)
// monthIndex is 0-11 (January = 0)
const fromComponents = new Date(2024, 0, 15, 14, 30, 0);
console.log(fromComponents); // Jan 15, 2024, 2:30:00 PM
// Date only (year, monthIndex, day)
const dateOnly = new Date(2024, 0, 15);
console.log(dateOnly); // Midnight local timeconst date = new Date(2024, 0, 15, 14, 30, 45, 123);
// Local time methods
console.log(date.getFullYear()); // 2024 (year)
console.log(date.getMonth()); // 0 (January = 0)
console.log(date.getDate()); // 15 (day of month)
console.log(date.getDay()); // 1 (Monday = 1, Sunday = 0)
console.log(date.getHours()); // 14 (0-23)
console.log(date.getMinutes()); // 30
console.log(date.getSeconds()); // 45
console.log(date.getMilliseconds()); // 123
// UTC methods (same as above but for UTC)
console.log(date.getUTCFullYear());
console.log(date.getUTCMonth());
console.log(date.getUTCDate());
console.log(date.getUTCHours());
console.log(date.getUTCMinutes());
// Other useful methods
console.log(date.getTime()); // Timestamp (ms since 1970)
console.log(date.getTimezoneOffset()); // Minutes between UTC and local
console.log(date.toDateString()); // "Mon Jan 15 2024"
console.log(date.toTimeString()); // "14:30:45 GMT-0500"
console.log(date.toISOString()); // "2024-01-15T19:30:45.123Z"
console.log(date.toJSON()); // Same as toISOStringconst date = new Date(2024, 0, 15);
// Set individual components
date.setFullYear(2025);
date.setMonth(5); // June (0-11)
date.setDate(20);
date.setHours(10, 30, 0, 0);
date.setMinutes(45);
date.setSeconds(30);
date.setMilliseconds(500);
// UTC setters
date.setUTCFullYear(2025);
date.setUTCMonth(5);
// Timestamp
date.setTime(1704067200000);
// Add days to a date
function addDays(date, days) {
const result = new Date(date);
result.setDate(result.getDate() + days);
return result;
}
console.log(addDays(new Date(2024, 0, 15), 10)); // Jan 25, 2024
console.log(addDays(new Date(2024, 0, 28), 5)); // Feb 2, 2024 (handles month overflow)const date = new Date(2024, 0, 15, 14, 30, 45);
// Built-in formats
console.log(date.toString()); // Full string
console.log(date.toDateString()); // "Mon Jan 15 2024"
console.log(date.toTimeString()); // "14:30:45 GMT-0500"
console.log(date.toISOString()); // "2024-01-15T19:30:45.123Z"
console.log(date.toJSON()); // "2024-01-15T19:30:45.123Z"
console.log(date.toUTCString()); // "Mon, 15 Jan 2024 19:30:45 GMT"
// Locale-specific formats
console.log(date.toLocaleString()); // "1/15/2024, 2:30:45 PM"
console.log(date.toLocaleDateString()); // "1/15/2024"
console.log(date.toLocaleTimeString()); // "2:30:45 PM"
console.log(date.toLocaleString('en-US')); // US format
console.log(date.toLocaleString('en-GB')); // UK format
// Custom formatting
function 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');
return format
.replace('YYYY', year)
.replace('MM', month)
.replace('DD', day)
.replace('HH', hours)
.replace('mm', minutes)
.replace('ss', seconds);
}
console.log(formatDate(new Date())); // "2024-01-15"
console.log(formatDate(new Date(), 'DD/MM/YYYY')); // "15/01/2024"
console.log(formatDate(new Date(), 'HH:mm:ss')); // "14:30:45"const date1 = new Date(2024, 0, 15);
const date2 = new Date(2024, 0, 20);
// Difference in milliseconds
const diff = date2 - date1;
console.log(diff / (1000 * 60 * 60 * 24)); // 5 days
// Difference in days
function daysBetween(date1, date2) {
const oneDay = 24 * 60 * 60 * 1000;
return Math.round(Math.abs(date1 - date2) / oneDay);
}
console.log(daysBetween(new Date(2024, 0, 1), new Date(2024, 0, 15))); // 14
// Add time periods
function addTime(date, amount, unit) {
const result = new Date(date);
switch (unit) {
case 'years':
result.setFullYear(result.getFullYear() + amount);
break;
case 'months':
result.setMonth(result.getMonth() + amount);
break;
case 'days':
result.setDate(result.getDate() + amount);
break;
case 'hours':
result.setHours(result.getHours() + amount);
break;
case 'minutes':
result.setMinutes(result.getMinutes() + amount);
break;
}
return result;
}
console.log(addTime(new Date(2024, 0, 15), 1, 'months'));
console.log(addTime(new Date(2024, 0, 15), 1, 'days'));
console.log(addTime(new Date(2024, 0, 15), 2, 'hours'));
// Start/end of day
function startOfDay(date) {
const result = new Date(date);
result.setHours(0, 0, 0, 0);
return result;
}
function endOfDay(date) {
const result = new Date(date);
result.setHours(23, 59, 59, 999);
return result;
}const date1 = new Date(2024, 0, 15);
const date2 = new Date(2024, 0, 20);
const date3 = new Date(2024, 0, 15);
// Direct comparison (uses timestamps)
console.log(date1 < date2); // true
console.log(date1 > date2); // false
console.log(date1 === date3); // false (different objects)
// Compare timestamps
console.log(date1.getTime() === date3.getTime()); // true
// Check if same day
function isSameDay(date1, date2) {
return date1.getFullYear() === date2.getFullYear() &&
date1.getMonth() === date2.getMonth() &&
date1.getDate() === date2.getDate();
}
console.log(isSameDay(new Date(2024, 0, 15), new Date(2024, 0, 15))); // true
// Check if date is today
function isToday(date) {
return isSameDay(date, new Date());
}
console.log(isToday(new Date())); // true
// Check if date is in past/future
function isPast(date) {
return date < new Date();
}
function isFuture(date) {
return date > new Date();
}
console.log(isPast(new Date(2020, 0, 1))); // true
console.log(isFuture(new Date(2030, 0, 1))); // trueconst date = new Date(2024, 0, 15, 12, 0, 0);
// Get timezone info
console.log(date.toLocaleString('en-US', { timeZoneName: 'short' }));
console.log(date.toLocaleString('en-US', { timeZoneName: 'long' }));
// List available timezones
console.log(Intl.supportedValuesOf('timeZone'));
// Working with specific timezone
function toTimeZone(date, timeZone) {
return new Date(date.toLocaleString('en-US', { timeZone }));
}
console.log(toTimeZone(new Date(), 'America/New_York'));
console.log(toTimeZone(new Date(), 'Europe/London'));
console.log(toTimeZone(new Date(), 'Asia/Tokyo'));
// UTC helpers
const now = new Date();
const utc = new Date(now.toISOString());
console.log(now.toUTCString()); // "Mon, 15 Jan 2024 12:00:00 GMT"
// Get timezone offset
const offset = date.getTimezoneOffset();
console.log(offset); // -300 (minutes, UTC-5)function calculateAge(birthDate) {
const today = new Date();
const birth = new Date(birthDate);
let age = today.getFullYear() - birth.getFullYear();
const monthDiff = today.getMonth() - birth.getMonth();
if (monthDiff < 0 || (monthDiff === 0 && today.getDate() < birth.getDate())) {
age--;
}
return age;
}
console.log(calculateAge("1990-05-15")); // Years since 1990
// More detailed
function calculateDetailedAge(birthDate) {
const today = new Date();
const birth = new Date(birthDate);
let years = today.getFullYear() - birth.getFullYear();
let months = today.getMonth() - birth.getMonth();
let days = today.getDate() - birth.getDate();
if (days < 0) {
months--;
days += new Date(today.getFullYear(), today.getMonth(), 0).getDate();
}
if (months < 0) {
years--;
months += 12;
}
return { years, months, days };
}function countdown(targetDate) {
const now = new Date();
const target = new Date(targetDate);
const diff = target - now;
if (diff <= 0) {
return "Event 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));
const seconds = Math.floor((diff % (1000 * 60)) / 1000);
return { days, hours, minutes, seconds };
}
console.log(countdown("2025-01-01T00:00:00"));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;
}
console.log(getDateRange("2024-01-01", "2024-01-05"));
// [Jan 1, Jan 2, Jan 3, Jan 4, Jan 5]
// Workdays only
function getWorkdays(startDate, endDate) {
const dates = [];
const current = new Date(startDate);
const end = new Date(endDate);
while (current <= end) {
const day = current.getDay();
if (day !== 0 && day !== 6) { // Not Sunday or Saturday
dates.push(new Date(current));
}
current.setDate(current.getDate() + 1);
}
return dates;
}function getWeekNumber(date) {
const d = new Date(Date.UTC(date.getFullYear(), date.getMonth(), date.getDate()));
const dayNum = d.getUTCDay() || 7;
d.setUTCDate(d.getUTCDate() + 4 - dayNum);
const yearStart = new Date(Date.UTC(d.getUTCFullYear(), 0, 1));
return Math.ceil((((d - yearStart) / 86400000) + 1) / 7);
}
console.log(getWeekNumber(new Date(2024, 0, 15))); // Week numberfunction relativeTime(date) {
const now = new Date();
const past = new Date(date);
const diff = now - past;
const seconds = Math.floor(diff / 1000);
const minutes = Math.floor(seconds / 60);
const hours = Math.floor(minutes / 60);
const days = Math.floor(hours / 24);
const weeks = Math.floor(days / 7);
const months = Math.floor(days / 30);
const years = Math.floor(days / 365);
if (seconds < 60) return "just now";
if (minutes < 60) return `${minutes} minute${minutes > 1 ? 's' : ''} ago`;
if (hours < 24) return `${hours} hour${hours > 1 ? 's' : ''} ago`;
if (days < 7) return `${days} day${days > 1 ? 's' : ''} ago`;
if (weeks < 4) return `${weeks} week${weeks > 1 ? 's' : ''} ago`;
if (months < 12) return `${months} month${months > 1 ? 's' : ''} ago`;
return `${years} year${years > 1 ? 's' : ''} ago`;
}
console.log(relativeTime(new Date(Date.now() - 3600000))); // "1 hour ago"
console.log(relativeTime(new Date(Date.now() - 86400000))); // "1 day ago"For complex date handling, consider these libraries:
- date-fns - Modular date utilities
- Moment.js - Legacy date library (now in maintenance)
- Day.js - Moment.js alternative (2KB)
- Luxon - Modern date/time library
// date-fns examples
import { format, addDays, differenceInDays } from 'date-fns';
format(new Date(), 'yyyy-MM-dd');
addDays(new Date(), 5);
differenceInDays(date1, date2);
// Day.js examples
import dayjs from 'dayjs';
dayjs().format('YYYY-MM-DD');
dayjs().add(5, 'day');
dayjs('2024-01-15').diff(dayjs('2024-01-01'), 'day');