Skip to main content
โšก Calmops

Date and Time Handling in JavaScript

Date and Time Handling in JavaScript

Introduction

Working with dates and times is a common task in web development. JavaScript’s Date object provides methods for creating, parsing, and manipulating dates. In this article, you’ll learn how to work with dates effectively, handle timezones, and implement practical date/time patterns.

Creating Dates

Current Date and Time

// Create date for current moment
const now = new Date();
console.log(now); // 2025-12-18T10:30:45.123Z

// Get current timestamp (milliseconds since epoch)
const timestamp = Date.now();
console.log(timestamp); // 1734516645123

// Get timestamp from date
const date = new Date();
console.log(date.getTime()); // 1734516645123

Creating Specific Dates

// From string
const date1 = new Date('2025-12-18');
const date2 = new Date('2025-12-18T10:30:45');
const date3 = new Date('December 18, 2025');

// From components
const date4 = new Date(2025, 11, 18); // Month is 0-indexed
const date5 = new Date(2025, 11, 18, 10, 30, 45, 123);

// From timestamp
const date6 = new Date(1734516645123);

console.log(date1); // 2025-12-18T00:00:00.000Z
console.log(date4); // 2025-12-18T00:00:00.000Z

Getting Date Components

Individual Components

const date = new Date('2025-12-18T14:30:45');

console.log(date.getFullYear()); // 2025
console.log(date.getMonth()); // 11 (0-indexed, so December)
console.log(date.getDate()); // 18
console.log(date.getDay()); // 4 (0 = Sunday, 4 = Thursday)
console.log(date.getHours()); // 14
console.log(date.getMinutes()); // 30
console.log(date.getSeconds()); // 45
console.log(date.getMilliseconds()); // 0

Practical Examples

// Get day name
function getDayName(date) {
  const days = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
  return days[date.getDay()];
}

console.log(getDayName(new Date('2025-12-18'))); // 'Thursday'

// Get month name
function getMonthName(date) {
  const months = ['January', 'February', 'March', 'April', 'May', 'June',
                  'July', 'August', 'September', 'October', 'November', 'December'];
  return months[date.getMonth()];
}

console.log(getMonthName(new Date('2025-12-18'))); // 'December'

// Get age from birthdate
function getAge(birthDate) {
  const today = new Date();
  let age = today.getFullYear() - birthDate.getFullYear();
  const monthDiff = today.getMonth() - birthDate.getMonth();
  
  if (monthDiff < 0 || (monthDiff === 0 && today.getDate() < birthDate.getDate())) {
    age--;
  }
  
  return age;
}

console.log(getAge(new Date('1995-06-15'))); // Current age

Setting Date Components

Modifying Dates

const date = new Date('2025-12-18T14:30:45');

// Set individual components
date.setFullYear(2026);
date.setMonth(0); // January
date.setDate(1);
date.setHours(0);
date.setMinutes(0);
date.setSeconds(0);

console.log(date); // 2026-01-01T00:00:00.000Z

// Practical example: Set to start of day
function startOfDay(date) {
  const newDate = new Date(date);
  newDate.setHours(0, 0, 0, 0);
  return newDate;
}

console.log(startOfDay(new Date())); // Today at 00:00:00

// Practical example: Set to end of day
function endOfDay(date) {
  const newDate = new Date(date);
  newDate.setHours(23, 59, 59, 999);
  return newDate;
}

console.log(endOfDay(new Date())); // Today at 23:59:59

Date Formatting

Basic Formatting

const date = new Date('2025-12-18T14:30:45');

// toString methods
console.log(date.toString()); // 'Thu Dec 18 2025 14:30:45 GMT+0000'
console.log(date.toDateString()); // 'Thu Dec 18 2025'
console.log(date.toTimeString()); // '14:30:45 GMT+0000'
console.log(date.toISOString()); // '2025-12-18T14:30:45.000Z'
console.log(date.toLocaleString()); // Locale-specific format
console.log(date.toLocaleDateString()); // Locale-specific date
console.log(date.toLocaleTimeString()); // Locale-specific time

Custom Formatting

// Format date as YYYY-MM-DD
function 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('2025-12-18'))); // '2025-12-18'

// Format date as DD/MM/YYYY
function formatDateUS(date) {
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  const year = date.getFullYear();
  return `${month}/${day}/${year}`;
}

console.log(formatDateUS(new Date('2025-12-18'))); // '12/18/2025'

// Format time as HH:MM:SS
function formatTime(date) {
  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 `${hours}:${minutes}:${seconds}`;
}

console.log(formatTime(new Date('2025-12-18T14:30:45'))); // '14:30:45'

Date Arithmetic

Adding/Subtracting Time

// Add days
function addDays(date, days) {
  const result = new Date(date);
  result.setDate(result.getDate() + days);
  return result;
}

console.log(addDays(new Date('2025-12-18'), 5)); // 2025-12-23

// Add months
function addMonths(date, months) {
  const result = new Date(date);
  result.setMonth(result.getMonth() + months);
  return result;
}

console.log(addMonths(new Date('2025-12-18'), 2)); // 2026-02-18

// Add hours
function addHours(date, hours) {
  const result = new Date(date);
  result.setHours(result.getHours() + hours);
  return result;
}

console.log(addHours(new Date('2025-12-18T10:00:00'), 3)); // 2025-12-18T13:00:00

// Subtract days
function subtractDays(date, days) {
  return addDays(date, -days);
}

console.log(subtractDays(new Date('2025-12-18'), 5)); // 2025-12-13

Date Comparison

Comparing Dates

const date1 = new Date('2025-12-18');
const date2 = new Date('2025-12-25');

// Direct comparison
console.log(date1 < date2); // true
console.log(date1 > date2); // false
console.log(date1.getTime() === date2.getTime()); // false

// Practical example: Check if date is today
function isToday(date) {
  const today = new Date();
  return date.getDate() === today.getDate() &&
         date.getMonth() === today.getMonth() &&
         date.getFullYear() === today.getFullYear();
}

console.log(isToday(new Date())); // true

// Practical example: Check if date is in past
function isPast(date) {
  return date < new Date();
}

console.log(isPast(new Date('2020-01-01'))); // true

// Practical example: Check if date is in future
function isFuture(date) {
  return date > new Date();
}

console.log(isFuture(new Date('2030-01-01'))); // true

Date Ranges and Intervals

Working with Ranges

// Get days between dates
function daysBetween(date1, date2) {
  const msPerDay = 24 * 60 * 60 * 1000;
  return Math.floor(Math.abs(date2 - date1) / msPerDay);
}

console.log(daysBetween(new Date('2025-12-18'), new Date('2025-12-25'))); // 7

// Get all dates in range
function dateRange(startDate, endDate) {
  const dates = [];
  const currentDate = new Date(startDate);
  
  while (currentDate <= endDate) {
    dates.push(new Date(currentDate));
    currentDate.setDate(currentDate.getDate() + 1);
  }
  
  return dates;
}

const dates = dateRange(new Date('2025-12-18'), new Date('2025-12-22'));
console.log(dates.length); // 5

// Check if date is in range
function isInRange(date, startDate, endDate) {
  return date >= startDate && date <= endDate;
}

console.log(isInRange(new Date('2025-12-20'), new Date('2025-12-18'), new Date('2025-12-25'))); // true

Real-World Examples

Example 1: Countdown Timer

// Countdown to specific date
function countdown(targetDate) {
  const now = new Date();
  const diff = targetDate - now;
  
  if (diff <= 0) {
    return { days: 0, hours: 0, minutes: 0, seconds: 0 };
  }
  
  return {
    days: Math.floor(diff / (1000 * 60 * 60 * 24)),
    hours: Math.floor((diff / (1000 * 60 * 60)) % 24),
    minutes: Math.floor((diff / 1000 / 60) % 60),
    seconds: Math.floor((diff / 1000) % 60)
  };
}

const target = new Date('2026-01-01');
console.log(countdown(target));
// { days: 13, hours: 13, minutes: 29, seconds: 15 }

Example 2: Business Days Calculator

// Count business days between dates
function businessDaysBetween(startDate, endDate) {
  let count = 0;
  const currentDate = new Date(startDate);
  
  while (currentDate <= endDate) {
    const dayOfWeek = currentDate.getDay();
    if (dayOfWeek !== 0 && dayOfWeek !== 6) { // Not Sunday or Saturday
      count++;
    }
    currentDate.setDate(currentDate.getDate() + 1);
  }
  
  return count;
}

console.log(businessDaysBetween(new Date('2025-12-18'), new Date('2025-12-25'))); // 5

Example 3: Age and Birthday

// Check if birthday is today
function isBirthdayToday(birthDate) {
  const today = new Date();
  return birthDate.getMonth() === today.getMonth() &&
         birthDate.getDate() === today.getDate();
}

// Get next birthday
function getNextBirthday(birthDate) {
  const today = new Date();
  let nextBirthday = new Date(today.getFullYear(), birthDate.getMonth(), birthDate.getDate());
  
  if (nextBirthday < today) {
    nextBirthday.setFullYear(today.getFullYear() + 1);
  }
  
  return nextBirthday;
}

// Days until birthday
function daysUntilBirthday(birthDate) {
  const nextBirthday = getNextBirthday(birthDate);
  return daysBetween(new Date(), nextBirthday);
}

Example 4: Schedule Formatter

// Format schedule with relative time
function formatSchedule(date) {
  const now = new Date();
  const diff = date - now;
  const msPerMinute = 60 * 1000;
  const msPerHour = 60 * msPerMinute;
  const msPerDay = 24 * msPerHour;
  
  if (diff < msPerMinute) {
    return 'Just now';
  } else if (diff < msPerHour) {
    return `In ${Math.floor(diff / msPerMinute)} minutes`;
  } else if (diff < msPerDay) {
    return `In ${Math.floor(diff / msPerHour)} hours`;
  } else {
    return `In ${Math.floor(diff / msPerDay)} days`;
  }
}

console.log(formatSchedule(new Date(Date.now() + 30 * 60 * 1000))); // 'In 30 minutes'

Common Mistakes to Avoid

Mistake 1: Month is 0-Indexed

// โŒ Wrong - Expecting month 12 for December
const date = new Date(2025, 12, 18); // Actually January 18, 2026

// โœ… Correct - Use 11 for December
const date = new Date(2025, 11, 18); // December 18, 2025

Mistake 2: Mutating Original Date

// โŒ Wrong - Modifies original
const original = new Date('2025-12-18');
const modified = original;
modified.setDate(25);
console.log(original.getDate()); // 25 (changed!)

// โœ… Correct - Create new date
const original = new Date('2025-12-18');
const modified = new Date(original);
modified.setDate(25);
console.log(original.getDate()); // 18 (unchanged)

Mistake 3: Timezone Issues

// โŒ Wrong - Ignoring timezone
const date = new Date('2025-12-18'); // Interpreted as UTC

// โœ… Correct - Be aware of timezone
const date = new Date('2025-12-18T14:30:45'); // Specific time
console.log(date.toLocaleString()); // Local timezone

Summary

Date handling is essential for web development:

  • Create dates from strings, components, or timestamps
  • Get individual date components
  • Format dates for display
  • Perform date arithmetic
  • Compare dates
  • Calculate date ranges
  • Handle timezones carefully
  • Use helper functions for common operations
  • Remember month is 0-indexed
  • Create new dates instead of mutating

Next Steps

Continue your learning journey:

Comments