javascript

examples

examples.js
/**
 * 15.2 Date Formatting & Calculations - Examples
 *
 * Comprehensive examples of date formatting, arithmetic, and calculations.
 */

// ============================================
// 1. BUILT-IN FORMATTING METHODS
// ============================================

console.log('=== Built-in Formatting Methods ===');

const date = new Date('2024-12-25T10:30:45.123');
console.log('Original date:', date);

console.log('\n--- String Methods ---');
console.log('toString():', date.toString());
console.log('toDateString():', date.toDateString());
console.log('toTimeString():', date.toTimeString());
console.log('toISOString():', date.toISOString());
console.log('toUTCString():', date.toUTCString());
console.log('toJSON():', date.toJSON());

console.log('\n--- Locale Methods ---');
console.log('toLocaleString():', date.toLocaleString());
console.log('toLocaleDateString():', date.toLocaleDateString());
console.log('toLocaleTimeString():', date.toLocaleTimeString());

// ============================================
// 2. INTL.DATETIMEFORMAT
// ============================================

console.log('\n=== Intl.DateTimeFormat ===');

// Different locales
console.log('--- Different Locales ---');
console.log('en-US:', new Intl.DateTimeFormat('en-US').format(date));
console.log('de-DE:', new Intl.DateTimeFormat('de-DE').format(date));
console.log('ja-JP:', new Intl.DateTimeFormat('ja-JP').format(date));
console.log('ar-SA:', new Intl.DateTimeFormat('ar-SA').format(date));
console.log('fr-FR:', new Intl.DateTimeFormat('fr-FR').format(date));

// With options
console.log('\n--- Formatting Options ---');

const fullFormatter = new Intl.DateTimeFormat('en-US', {
  weekday: 'long',
  year: 'numeric',
  month: 'long',
  day: 'numeric',
});
console.log('Full date:', fullFormatter.format(date));

const shortFormatter = new Intl.DateTimeFormat('en-US', {
  year: '2-digit',
  month: '2-digit',
  day: '2-digit',
});
console.log('Short date:', shortFormatter.format(date));

const timeFormatter = new Intl.DateTimeFormat('en-US', {
  hour: '2-digit',
  minute: '2-digit',
  second: '2-digit',
  hour12: true,
});
console.log('Time (12-hour):', timeFormatter.format(date));

const time24Formatter = new Intl.DateTimeFormat('en-US', {
  hour: '2-digit',
  minute: '2-digit',
  hour12: false,
});
console.log('Time (24-hour):', time24Formatter.format(date));

// Different option values
console.log('\n--- Weekday Options ---');
console.log(
  'narrow:',
  new Intl.DateTimeFormat('en-US', { weekday: 'narrow' }).format(date)
);
console.log(
  'short:',
  new Intl.DateTimeFormat('en-US', { weekday: 'short' }).format(date)
);
console.log(
  'long:',
  new Intl.DateTimeFormat('en-US', { weekday: 'long' }).format(date)
);

console.log('\n--- Month Options ---');
console.log(
  'numeric:',
  new Intl.DateTimeFormat('en-US', { month: 'numeric' }).format(date)
);
console.log(
  '2-digit:',
  new Intl.DateTimeFormat('en-US', { month: '2-digit' }).format(date)
);
console.log(
  'narrow:',
  new Intl.DateTimeFormat('en-US', { month: 'narrow' }).format(date)
);
console.log(
  'short:',
  new Intl.DateTimeFormat('en-US', { month: 'short' }).format(date)
);
console.log(
  'long:',
  new Intl.DateTimeFormat('en-US', { month: 'long' }).format(date)
);

// With timezone
console.log('\n--- Timezone Options ---');
const tzFormatter = new Intl.DateTimeFormat('en-US', {
  timeZone: 'America/New_York',
  hour: '2-digit',
  minute: '2-digit',
  timeZoneName: 'short',
});
console.log('New York:', tzFormatter.format(date));

const tokyoFormatter = new Intl.DateTimeFormat('en-US', {
  timeZone: 'Asia/Tokyo',
  hour: '2-digit',
  minute: '2-digit',
  timeZoneName: 'short',
});
console.log('Tokyo:', tokyoFormatter.format(date));

// ============================================
// 3. CUSTOM FORMAT FUNCTION
// ============================================

console.log('\n=== Custom Format Function ===');

function formatDate(date, format) {
  const map = {
    YYYY: date.getFullYear(),
    YY: String(date.getFullYear()).slice(-2),
    MM: String(date.getMonth() + 1).padStart(2, '0'),
    M: date.getMonth() + 1,
    DD: String(date.getDate()).padStart(2, '0'),
    D: date.getDate(),
    HH: String(date.getHours()).padStart(2, '0'),
    H: date.getHours(),
    mm: String(date.getMinutes()).padStart(2, '0'),
    m: date.getMinutes(),
    ss: String(date.getSeconds()).padStart(2, '0'),
    s: date.getSeconds(),
  };

  return format.replace(
    /YYYY|YY|MM|M|DD|D|HH|H|mm|m|ss|s/g,
    (match) => map[match]
  );
}

console.log('YYYY-MM-DD:', formatDate(date, 'YYYY-MM-DD'));
console.log('DD/MM/YYYY:', formatDate(date, 'DD/MM/YYYY'));
console.log('M/D/YY:', formatDate(date, 'M/D/YY'));
console.log('YYYY-MM-DD HH:mm:ss:', formatDate(date, 'YYYY-MM-DD HH:mm:ss'));
console.log('HH:mm:', formatDate(date, 'HH:mm'));

// ============================================
// 4. DATE ARITHMETIC
// ============================================

console.log('\n=== Date Arithmetic ===');

// Time constants
const MS_PER_SECOND = 1000;
const MS_PER_MINUTE = 60 * MS_PER_SECOND;
const MS_PER_HOUR = 60 * MS_PER_MINUTE;
const MS_PER_DAY = 24 * MS_PER_HOUR;
const MS_PER_WEEK = 7 * MS_PER_DAY;

console.log('--- Time Constants (ms) ---');
console.log('MS_PER_SECOND:', MS_PER_SECOND);
console.log('MS_PER_MINUTE:', MS_PER_MINUTE);
console.log('MS_PER_HOUR:', MS_PER_HOUR);
console.log('MS_PER_DAY:', MS_PER_DAY);
console.log('MS_PER_WEEK:', MS_PER_WEEK);

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

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

// Add/subtract years
function addYears(date, years) {
  const result = new Date(date);
  result.setFullYear(result.getFullYear() + years);
  return result;
}

// Add/subtract hours
function addHours(date, hours) {
  return new Date(date.getTime() + hours * MS_PER_HOUR);
}

// Add/subtract minutes
function addMinutes(date, minutes) {
  return new Date(date.getTime() + minutes * MS_PER_MINUTE);
}

const today = new Date('2024-12-25');
console.log('\n--- Adding Time ---');
console.log('Today:', today.toDateString());
console.log('+ 7 days:', addDays(today, 7).toDateString());
console.log('- 7 days:', addDays(today, -7).toDateString());
console.log('+ 1 month:', addMonths(today, 1).toDateString());
console.log('- 1 month:', addMonths(today, -1).toDateString());
console.log('+ 1 year:', addYears(today, 1).toDateString());

const now = new Date();
console.log('\nNow:', now.toTimeString());
console.log('+ 2 hours:', addHours(now, 2).toTimeString());
console.log('+ 30 minutes:', addMinutes(now, 30).toTimeString());

// ============================================
// 5. CALCULATING DIFFERENCES
// ============================================

console.log('\n=== Calculating Differences ===');

function dateDiff(date1, date2) {
  const ms = Math.abs(date2 - date1);

  return {
    milliseconds: ms,
    seconds: Math.floor(ms / 1000),
    minutes: Math.floor(ms / (1000 * 60)),
    hours: Math.floor(ms / (1000 * 60 * 60)),
    days: Math.floor(ms / (1000 * 60 * 60 * 24)),
    weeks: Math.floor(ms / (1000 * 60 * 60 * 24 * 7)),
  };
}

const start = new Date('2024-01-01');
const end = new Date('2024-12-31');
const diff = dateDiff(start, end);

console.log('From:', start.toDateString());
console.log('To:', end.toDateString());
console.log('Difference:');
console.log('  Days:', diff.days);
console.log('  Weeks:', diff.weeks);
console.log('  Hours:', diff.hours);

// Difference in specific units
function diffInDays(date1, date2) {
  const oneDay = 24 * 60 * 60 * 1000;
  return Math.round((date2 - date1) / oneDay);
}

function diffInMonths(date1, date2) {
  let months = (date2.getFullYear() - date1.getFullYear()) * 12;
  months += date2.getMonth() - date1.getMonth();
  return months;
}

console.log('\n--- Specific Differences ---');
console.log('Days between:', diffInDays(start, end));
console.log('Months between:', diffInMonths(start, end));

// ============================================
// 6. RELATIVE TIME
// ============================================

console.log('\n=== Relative Time ===');

// Using Intl.RelativeTimeFormat
const rtf = new Intl.RelativeTimeFormat('en', { numeric: 'auto' });

console.log('--- Intl.RelativeTimeFormat ---');
console.log('-1 day:', rtf.format(-1, 'day'));
console.log('-2 days:', rtf.format(-2, 'day'));
console.log('+1 day:', rtf.format(1, 'day'));
console.log('-1 week:', rtf.format(-1, 'week'));
console.log('-1 month:', rtf.format(-1, 'month'));
console.log('-1 year:', rtf.format(-1, 'year'));

// Custom relative time function
function getRelativeTime(date, baseDate = new Date()) {
  const rtf = new Intl.RelativeTimeFormat('en', { numeric: 'auto' });
  const diff = date - baseDate;
  const absDiff = Math.abs(diff);

  const seconds = absDiff / 1000;
  const minutes = seconds / 60;
  const hours = minutes / 60;
  const days = hours / 24;
  const weeks = days / 7;
  const months = days / 30;
  const years = days / 365;

  const sign = diff < 0 ? -1 : 1;

  if (seconds < 60) {
    return rtf.format(Math.round(seconds) * sign, 'second');
  } else if (minutes < 60) {
    return rtf.format(Math.round(minutes) * sign, 'minute');
  } else if (hours < 24) {
    return rtf.format(Math.round(hours) * sign, 'hour');
  } else if (days < 7) {
    return rtf.format(Math.round(days) * sign, 'day');
  } else if (weeks < 4) {
    return rtf.format(Math.round(weeks) * sign, 'week');
  } else if (months < 12) {
    return rtf.format(Math.round(months) * sign, 'month');
  } else {
    return rtf.format(Math.round(years) * sign, 'year');
  }
}

console.log('\n--- Custom Relative Time ---');
console.log('5 seconds ago:', getRelativeTime(new Date(Date.now() - 5000)));
console.log(
  '2 hours ago:',
  getRelativeTime(new Date(Date.now() - 2 * 60 * 60 * 1000))
);
console.log(
  'Tomorrow:',
  getRelativeTime(new Date(Date.now() + 24 * 60 * 60 * 1000))
);

// Simple time ago
function timeAgo(date) {
  const seconds = Math.floor((new Date() - date) / 1000);

  const intervals = {
    year: 31536000,
    month: 2592000,
    week: 604800,
    day: 86400,
    hour: 3600,
    minute: 60,
    second: 1,
  };

  for (const [unit, secondsInUnit] of Object.entries(intervals)) {
    const interval = Math.floor(seconds / secondsInUnit);
    if (interval >= 1) {
      return `${interval} ${unit}${interval === 1 ? '' : 's'} ago`;
    }
  }

  return 'just now';
}

console.log('\n--- Simple Time Ago ---');
console.log(timeAgo(new Date(Date.now() - 30000))); // 30 seconds ago
console.log(timeAgo(new Date(Date.now() - 3600000))); // 1 hour ago
console.log(timeAgo(new Date(Date.now() - 86400000 * 3))); // 3 days ago

// ============================================
// 7. DATE RANGES
// ============================================

console.log('\n=== Date Ranges ===');

// Date range generator
function* dateRange(startDate, endDate, step = 1) {
  const current = new Date(startDate);
  while (current <= endDate) {
    yield new Date(current);
    current.setDate(current.getDate() + step);
  }
}

console.log('--- Date Range (Jan 1-7, 2024) ---');
const rangeStart = new Date('2024-01-01');
const rangeEnd = new Date('2024-01-07');

for (const d of dateRange(rangeStart, rangeEnd)) {
  console.log(d.toDateString());
}

// Get all days in month
function getDaysInMonth(year, month) {
  const date = new Date(year, month, 1);
  const days = [];

  while (date.getMonth() === month) {
    days.push(new Date(date));
    date.setDate(date.getDate() + 1);
  }

  return days;
}

console.log('\n--- Days in February 2024 ---');
const feb2024 = getDaysInMonth(2024, 1); // Month 1 = February
console.log('Number of days:', feb2024.length);
console.log(
  'First day:',
  feb2024[0].toDateString(),
  '| Last day:',
  feb2024[feb2024.length - 1].toDateString()
);

// ============================================
// 8. BUSINESS DAYS
// ============================================

console.log('\n=== Business Days ===');

function isWeekend(date) {
  const day = date.getDay();
  return day === 0 || day === 6;
}

function addBusinessDays(date, days) {
  const result = new Date(date);
  let added = 0;

  while (added < days) {
    result.setDate(result.getDate() + 1);
    if (!isWeekend(result)) {
      added++;
    }
  }

  return result;
}

function getBusinessDaysBetween(startDate, endDate) {
  let count = 0;
  const current = new Date(startDate);

  while (current < endDate) {
    current.setDate(current.getDate() + 1);
    if (!isWeekend(current)) {
      count++;
    }
  }

  return count;
}

const monday = new Date('2024-12-23'); // Monday
console.log('Starting:', monday.toDateString());
console.log('+ 5 business days:', addBusinessDays(monday, 5).toDateString());

const monthStart = new Date('2024-12-01');
const monthEnd = new Date('2024-12-31');
console.log(
  '\nBusiness days in Dec 2024:',
  getBusinessDaysBetween(monthStart, monthEnd)
);

// ============================================
// 9. COMMON CALCULATIONS
// ============================================

console.log('\n=== Common Calculations ===');

// Age calculator
function calculateAge(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('--- Age Calculator ---');
console.log('Born 1990-05-15, age:', calculateAge(new Date('1990-05-15')));
console.log('Born 2000-01-01, age:', calculateAge(new Date('2000-01-01')));

// Days until/since
function daysUntil(targetDate) {
  const today = new Date();
  today.setHours(0, 0, 0, 0);
  const target = new Date(targetDate);
  target.setHours(0, 0, 0, 0);

  return Math.ceil((target - today) / (1000 * 60 * 60 * 24));
}

console.log('\n--- Days Until ---');
console.log('Days until New Year 2025:', daysUntil(new Date('2025-01-01')));

// Next occurrence of weekday
function getNextWeekday(dayOfWeek) {
  const today = new Date();
  const currentDay = today.getDay();
  const daysUntilNext = (dayOfWeek - currentDay + 7) % 7 || 7;

  const next = new Date(today);
  next.setDate(today.getDate() + daysUntilNext);
  return next;
}

console.log('\n--- Next Weekday ---');
console.log('Next Monday:', getNextWeekday(1).toDateString());
console.log('Next Friday:', getNextWeekday(5).toDateString());
console.log('Next Sunday:', getNextWeekday(0).toDateString());

// ============================================
// 10. CALENDAR HELPERS
// ============================================

console.log('\n=== Calendar Helpers ===');

function getCalendarMonth(year, month) {
  const firstDay = new Date(year, month, 1);
  const lastDay = new Date(year, month + 1, 0);

  const calendar = [];
  let week = [];

  // Pad the beginning with nulls
  for (let i = 0; i < firstDay.getDay(); i++) {
    week.push(null);
  }

  // Add all days
  for (let day = 1; day <= lastDay.getDate(); day++) {
    week.push(day);
    if (week.length === 7) {
      calendar.push(week);
      week = [];
    }
  }

  // Pad the end with nulls
  while (week.length > 0 && week.length < 7) {
    week.push(null);
  }
  if (week.length) calendar.push(week);

  return calendar;
}

console.log('--- December 2024 Calendar ---');
const cal = getCalendarMonth(2024, 11);
console.log('Su Mo Tu We Th Fr Sa');
for (const week of cal) {
  console.log(week.map((d) => (d ? String(d).padStart(2) : '  ')).join(' '));
}

// Get week number
function getWeekNumber(date) {
  const d = new Date(date);
  d.setHours(0, 0, 0, 0);
  d.setDate(d.getDate() + 4 - (d.getDay() || 7));
  const yearStart = new Date(d.getFullYear(), 0, 1);
  return Math.ceil(((d - yearStart) / 86400000 + 1) / 7);
}

console.log('\n--- Week Numbers ---');
console.log('Week of Jan 1, 2024:', getWeekNumber(new Date('2024-01-01')));
console.log('Week of Dec 25, 2024:', getWeekNumber(new Date('2024-12-25')));

console.log('\n=== Examples Complete ===');
Examples - JavaScript Tutorial | DeepML