Web Date Time TypeScript Samples

Web TypeScript date and time examples including getting current time, formatting, parsing, and manipulation

Key Facts

Category
TypeScript
Items
3
Format Families
text

Sample Overview

Web TypeScript date and time examples including getting current time, formatting, parsing, and manipulation This sample set belongs to TypeScript and can be used to test related workflows inside Elysia Tools.

💻 Get Current Time typescript

🟢 simple ⭐⭐

Retrieve current date and time in various formats and timezones using Date API

⏱️ 15 min 🏷️ typescript, web, datetime
Prerequisites: Basic TypeScript, Date API
// Web TypeScript Get Current Time Examples
// Retrieving current date and time in various formats and timezones

// 1. Basic Time Retrieval
class TimeRetriever {
  // Get current date
  static getCurrentDate(): Date {
    return new Date();
  }

  // Get current timestamp
  static getCurrentTimestamp(): number {
    return Date.now();
  }

  // Get current time in milliseconds
  static getCurrentTimeMillis(): number {
    return new Date().getTime();
  }

  // Get current UTC date
  static getCurrentUTCDate(): Date {
    return new Date();
  }

  // Get current ISO string
  static getCurrentISOString(): string {
    return new Date().toISOString();
  }

  // Get current date string
  static getCurrentDateString(): string {
    return new Date().toDateString();
  }

  // Get current time string
  static getCurrentTimeString(): string {
    return new Date().toTimeString();
  }

  // Get current locale string
  static getCurrentLocaleString(locale?: string): string {
    return new Date().toLocaleString(locale);
  }

  // Get current UTC string
  static getCurrentUTCString(): string {
    return new Date().toUTCString();
  }
}

// 2. Time Components Extraction
class TimeComponents {
  // Get year
  static getYear(date: Date = new Date()): number {
    return date.getFullYear();
  }

  // Get month (0-11)
  static getMonth(date: Date = new Date()): number {
    return date.getMonth();
  }

  // Get month name
  static getMonthName(date: Date = new Date(), locale: string = 'en-US'): string {
    return date.toLocaleString(locale, { month: 'long' });
  }

  // Get day of month
  static getDay(date: Date = new Date()): number {
    return date.getDate();
  }

  // Get day of week (0-6)
  static getDayOfWeek(date: Date = new Date()): number {
    return date.getDay();
  }

  // Get day of week name
  static getDayOfWeekName(date: Date = new Date(), locale: string = 'en-US'): string {
    return date.toLocaleString(locale, { weekday: 'long' });
  }

  // Get hours
  static getHours(date: Date = new Date()): number {
    return date.getHours();
  }

  // Get minutes
  static getMinutes(date: Date = new Date()): number {
    return date.getMinutes();
  }

  // Get seconds
  static getSeconds(date: Date = new Date()): number {
    return date.getSeconds();
  }

  // Get milliseconds
  static getMilliseconds(date: Date = new Date()): number {
    return date.getMilliseconds();
  }

  // Get all components as object
  static getAllComponents(date: Date = new Date()): {
    year: number;
    month: number;
    day: number;
    hours: number;
    minutes: number;
    seconds: number;
    milliseconds: number;
    dayOfWeek: number;
  } {
    return {
      year: date.getFullYear(),
      month: date.getMonth(),
      day: date.getDate(),
      hours: date.getHours(),
      minutes: date.getMinutes(),
      seconds: date.getSeconds(),
      milliseconds: date.getMilliseconds(),
      dayOfWeek: date.getDay()
    };
  }
}

// 3. UTC Time Components
class UTCTimeComponents {
  // Get UTC year
  static getUTCYear(date: Date = new Date()): number {
    return date.getUTCFullYear();
  }

  // Get UTC month
  static getUTCMonth(date: Date = new Date()): number {
    return date.getUTCMonth();
  }

  // Get UTC day
  static getUTCDay(date: Date = new Date()): number {
    return date.getUTCDate();
  }

  // Get UTC hours
  static getUTCHours(date: Date = new Date()): number {
    return date.getUTCHours();
  }

  // Get UTC minutes
  static getUTCMinutes(date: Date = new Date()): number {
    return date.getUTCMinutes();
  }

  // Get UTC seconds
  static getUTCSeconds(date: Date = new Date()): number {
    return date.getUTCSeconds();
  }

  // Get all UTC components
  static getAllUTCComponents(date: Date = new Date()): {
    year: number;
    month: number;
    day: number;
    hours: number;
    minutes: number;
    seconds: number;
    milliseconds: number;
  } {
    return {
      year: date.getUTCFullYear(),
      month: date.getUTCMonth(),
      day: date.getUTCDate(),
      hours: date.getUTCHours(),
      minutes: date.getUTCMinutes(),
      seconds: date.getUTCSeconds(),
      milliseconds: date.getUTCMilliseconds()
    };
  }
}

// 4. Timezone Information
class TimezoneInfo {
  // Get timezone offset in minutes
  static getTimezoneOffset(date: Date = new Date()): number {
    return date.getTimezoneOffset();
  }

  // Get timezone offset in hours
  static getTimezoneOffsetHours(date: Date = new Date()): number {
    return date.getTimezoneOffset() / 60;
  }

  // Get timezone name
  static getTimezoneName(): string {
    return Intl.DateTimeFormat().resolvedOptions().timeZone;
  }

  // Get local timezone string
  static getLocalTimezoneString(): string {
    const offset = new Date().getTimezoneOffset();
    const hours = Math.abs(Math.floor(offset / 60));
    const minutes = Math.abs(offset % 60);
    const sign = offset <= 0 ? '+' : '-';

    return `UTC${sign}${String(hours).padStart(2, '0')}:${String(minutes).padStart(2, '0')}`;
  }

  // Check if DST is in effect
  static isDST(date: Date = new Date()): boolean {
    const jan = new Date(date.getFullYear(), 0, 1).getTimezoneOffset();
    const jul = new Date(date.getFullYear(), 6, 1).getTimezoneOffset();
    const current = date.getTimezoneOffset();

    return current !== Math.max(jan, jul);
  }
}

// 5. High Resolution Time
class HighResolutionTime {
  // Get high resolution timestamp
  static getHighResolutionTime(): number {
    return performance.now();
  }

  // Measure time elapsed
  static measureTime(callback: () => void): number {
    const start = performance.now();
    callback();
    return performance.now() - start;
  }

  // Measure async time
  static async measureTimeAsync<T>(callback: () => Promise<T>): Promise<{ result: T; elapsed: number }> {
    const start = performance.now();
    const result = await callback();
    const elapsed = performance.now() - start;

    return { result, elapsed };
  }

  // Get time with microsecond precision (if available)
  static getPreciseTime(): { seconds: number; nanos: number } {
    const hrTime = typeof process !== 'undefined' && typeof process.hrtime === 'function'
      ? process.hrtime()
      : undefined;
    if (hrTime) {
      return { seconds: hrTime[0], nanos: hrTime[1] };
    }

    // Fallback for browser
    const now = Date.now();
    return { seconds: Math.floor(now / 1000), nanos: (now % 1000) * 1000000 };
  }
}

// 6. Relative Time
class RelativeTime {
  // Get start of day
  static getStartOfDay(date: Date = new Date()): Date {
    const result = new Date(date);
    result.setHours(0, 0, 0, 0);
    return result;
  }

  // Get end of day
  static getEndOfDay(date: Date = new Date()): Date {
    const result = new Date(date);
    result.setHours(23, 59, 59, 999);
    return result;
  }

  // Get start of week
  static getStartOfWeek(date: Date = new Date()): Date {
    const result = new Date(date);
    const day = result.getDay();
    const diff = result.getDate() - day;
    result.setDate(diff);
    result.setHours(0, 0, 0, 0);
    return result;
  }

  // Get end of week
  static getEndOfWeek(date: Date = new Date()): Date {
    const result = new Date(date);
    const day = result.getDay();
    const diff = result.getDate() - day + 6;
    result.setDate(diff);
    result.setHours(23, 59, 59, 999);
    return result;
  }

  // Get start of month
  static getStartOfMonth(date: Date = new Date()): Date {
    const result = new Date(date);
    result.setDate(1);
    result.setHours(0, 0, 0, 0);
    return result;
  }

  // Get end of month
  static getEndOfMonth(date: Date = new Date()): Date {
    const result = new Date(date);
    result.setMonth(result.getMonth() + 1);
    result.setDate(0);
    result.setHours(23, 59, 59, 999);
    return result;
  }

  // Get start of year
  static getStartOfYear(date: Date = new Date()): Date {
    const result = new Date(date);
    result.setMonth(0, 1);
    result.setHours(0, 0, 0, 0);
    return result;
  }

  // Get end of year
  static getEndOfYear(date: Date = new Date()): Date {
    const result = new Date(date);
    result.setMonth(11, 31);
    result.setHours(23, 59, 59, 999);
    return result;
  }
}

// 7. Time Utilities
class TimeUtilities {
  // Check if date is valid
  static isValid(date: Date): boolean {
    return date instanceof Date && !isNaN(date.getTime());
  }

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

  // Check if date is in the past
  static isPast(date: Date): boolean {
    return date < new Date();
  }

  // Check if date is in the future
  static isFuture(date: Date): boolean {
    return date > new Date();
  }

  // Get leap year
  static isLeapYear(year: number): boolean {
    return (year % 4 === 0 && year % 100 !== 0) || (year % 400 === 0);
  }

  // Get days in month
  static getDaysInMonth(year: number, month: number): number {
    return new Date(year, month + 1, 0).getDate();
  }

  // Compare two dates
  static compare(date1: Date, date2: Date): number {
    return date1.getTime() - date2.getTime();
  }

  // Get difference in days
  static getDaysDifference(date1: Date, date2: Date): number {
    const oneDay = 24 * 60 * 60 * 1000;
    return Math.round((date1.getTime() - date2.getTime()) / oneDay);
  }

  // Get age from birthdate
  static getAge(birthDate: Date): number {
    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;
  }
}

// 8. Time Formatting
class QuickFormatter {
  // Format as YYYY-MM-DD
  static toISODate(date: Date = new Date()): string {
    return date.toISOString().split('T')[0];
  }

  // Format as HH:mm:ss
  static toISOTime(date: Date = new Date()): string {
    return date.toTimeString().split(' ')[0];
  }

  // Format as YYYY-MM-DD HH:mm:ss
  static toISODateTime(date: Date = new Date()): string {
    return date.toISOString().replace('T', ' ').split('.')[0];
  }

  // Format locale date
  static toLocaleDate(date: Date = new Date(), locale: string = 'en-US'): string {
    return date.toLocaleDateString(locale);
  }

  // Format locale time
  static toLocaleTime(date: Date = new Date(), locale: string = 'en-US'): string {
    return date.toLocaleTimeString(locale);
  }

  // Format locale datetime
  static toLocaleDateTime(date: Date = new Date(), locale: string = 'en-US'): string {
    return date.toLocaleString(locale);
  }
}

// Usage Examples
async function demonstrateGetCurrentTime() {
  console.log('=== Web TypeScript Get Current Time Examples ===\n');

  // 1. Basic time retrieval
  console.log('--- 1. Basic Time Retrieval ---');
  const now = TimeRetriever.getCurrentDate();
  console.log(`Current date: ${now}`);
  console.log(`Current timestamp: ${TimeRetriever.getCurrentTimestamp()}`);
  console.log(`Current time millis: ${TimeRetriever.getCurrentTimeMillis()}`);
  console.log(`Current ISO string: ${TimeRetriever.getCurrentISOString()}`);
  console.log(`Current date string: ${TimeRetriever.getCurrentDateString()}`);
  console.log(`Current time string: ${TimeRetriever.getCurrentTimeString()}`);
  console.log(`Current locale string: ${TimeRetriever.getCurrentLocaleString()}`);

  // 2. Time components
  console.log('\n--- 2. Time Components ---');
  console.log(`Year: ${TimeComponents.getYear()}`);
  console.log(`Month: ${TimeComponents.getMonth()}`);
  console.log(`Month name: ${TimeComponents.getMonthName()}`);
  console.log(`Day: ${TimeComponents.getDay()}`);
  console.log(`Day of week: ${TimeComponents.getDayOfWeek()}`);
  console.log(`Day name: ${TimeComponents.getDayOfWeekName()}`);
  console.log(`Hours: ${TimeComponents.getHours()}`);
  console.log(`Minutes: ${TimeComponents.getMinutes()}`);
  console.log(`Seconds: ${TimeComponents.getSeconds()}`);

  const components = TimeComponents.getAllComponents();
  console.log(`All components: ${JSON.stringify(components)}`);

  // 3. UTC components
  console.log('\n--- 3. UTC Components ---');
  console.log(`UTC year: ${UTCTimeComponents.getUTCYear()}`);
  console.log(`UTC month: ${UTCTimeComponents.getUTCMonth()}`);
  console.log(`UTC day: ${UTCTimeComponents.getUTCDay()}`);
  console.log(`UTC hours: ${UTCTimeComponents.getUTCHours()}`);

  // 4. Timezone info
  console.log('\n--- 4. Timezone Info ---');
  console.log(`Timezone offset (minutes): ${TimezoneInfo.getTimezoneOffset()}`);
  console.log(`Timezone offset (hours): ${TimezoneInfo.getTimezoneOffsetHours()}`);
  console.log(`Timezone name: ${TimezoneInfo.getTimezoneName()}`);
  console.log(`Local timezone: ${TimezoneInfo.getLocalTimezoneString()}`);
  console.log(`Is DST: ${TimezoneInfo.isDST()}`);

  // 5. High resolution time
  console.log('\n--- 5. High Resolution Time ---');
  const start = performance.now();
  for (let i = 0; i < 1000; i++) {
    // Some work
  }
  const elapsed = performance.now() - start;
  console.log(`Elapsed time: ${elapsed.toFixed(2)}ms`);

  const measured = HighResolutionTime.measureTime(() => {
    let sum = 0;
    for (let i = 0; i < 10000; i++) {
      sum += i;
    }
  });
  console.log(`Measured time: ${measured.toFixed(2)}ms`);

  // 6. Relative time
  console.log('\n--- 6. Relative Time ---');
  console.log(`Start of day: ${RelativeTime.getStartOfDay()}`);
  console.log(`End of day: ${RelativeTime.getEndOfDay()}`);
  console.log(`Start of week: ${RelativeTime.getStartOfWeek()}`);
  console.log(`End of week: ${RelativeTime.getEndOfWeek()}`);
  console.log(`Start of month: ${RelativeTime.getStartOfMonth()}`);
  console.log(`End of month: ${RelativeTime.getEndOfMonth()}`);

  // 7. Time utilities
  console.log('\n--- 7. Time Utilities ---');
  console.log(`Is today: ${TimeUtilities.isToday(new Date())}`);
  console.log(`Is leap year: ${TimeUtilities.isLeapYear(2024)}`);
  console.log(`Days in Feb 2024: ${TimeUtilities.getDaysInMonth(2024, 1)}`);
  console.log(`Days in Feb 2023: ${TimeUtilities.getDaysInMonth(2023, 1)}`);

  const birthDate = new Date('1990-05-15');
  console.log(`Age from 1990-05-15: ${TimeUtilities.getAge(birthDate)}`);

  // 8. Quick formatting
  console.log('\n--- 8. Quick Formatting ---');
  console.log(`ISO date: ${QuickFormatter.toISODate()}`);
  console.log(`ISO time: ${QuickFormatter.toISOTime()}`);
  console.log(`ISO datetime: ${QuickFormatter.toISODateTime()}`);
  console.log(`Locale date: ${QuickFormatter.toLocaleDate()}`);
  console.log(`Locale time: ${QuickFormatter.toLocaleTime()}`);
  console.log(`Locale datetime: ${QuickFormatter.toLocaleDateTime()}`);

  console.log('\n=== All Get Current Time Examples Completed ===');
}

// Export classes
export { TimeRetriever, TimeComponents, UTCTimeComponents, TimezoneInfo, HighResolutionTime, RelativeTime, TimeUtilities, QuickFormatter };
export { demonstrateGetCurrentTime };

💻 Date Time Formatting typescript

🟡 intermediate ⭐⭐⭐

Format dates and times into various string representations using Intl API and custom formatters

⏱️ 25 min 🏷️ typescript, web, datetime, formatting
Prerequisites: Intermediate TypeScript, Intl API
// Web TypeScript Date Time Formatting Examples
// Comprehensive date and time formatting using Intl API and custom formatters

// 1. Basic Formatting
class BasicFormatter {
  // Format to ISO string
  static toISOString(date: Date = new Date()): string {
    return date.toISOString();
  }

  // Format to locale string
  static toLocaleString(date: Date = new Date(), locale: string = 'en-US'): string {
    return date.toLocaleString(locale);
  }

  // Format to locale date
  static toLocaleDateString(date: Date = new Date(), locale: string = 'en-US'): string {
    return date.toLocaleDateString(locale);
  }

  // Format to locale time
  static toLocaleTimeString(date: Date = new Date(), locale: string = 'en-US'): string {
    return date.toLocaleTimeString(locale);
  }

  // Format to UTC string
  static toUTCString(date: Date = new Date()): string {
    return date.toUTCString();
  }

  // Format to date string
  static toDateString(date: Date = new Date()): string {
    return date.toDateString();
  }

  // Format to time string
  static toTimeString(date: Date = new Date()): string {
    return date.toTimeString();
  }
}

// 2. Intl DateTime Format
class IntlFormatter {
  // Format with custom options
  static format(
    date: Date,
    options: Intl.DateTimeFormatOptions,
    locale: string = 'en-US'
  ): string {
    return new Intl.DateTimeFormat(locale, options).format(date);
  }

  // Format date only
  static formatDate(date: Date, locale: string = 'en-US'): string {
    return this.format(date, {
      year: 'numeric',
      month: 'long',
      day: 'numeric'
    }, locale);
  }

  // Format time only
  static formatTime(date: Date, locale: string = 'en-US'): string {
    return this.format(date, {
      hour: '2-digit',
      minute: '2-digit',
      second: '2-digit'
    }, locale);
  }

  // Format full
  static formatFull(date: Date, locale: string = 'en-US'): string {
    return this.format(date, {
      weekday: 'long',
      year: 'numeric',
      month: 'long',
      day: 'numeric',
      hour: '2-digit',
      minute: '2-digit',
      second: '2-digit',
      timeZoneName: 'long'
    }, locale);
  }

  // Format short
  static formatShort(date: Date, locale: string = 'en-US'): string {
    return this.format(date, {
      year: 'numeric',
      month: 'short',
      day: 'numeric'
    }, locale);
  }

  // Format medium
  static formatMedium(date: Date, locale: string = 'en-US'): string {
    return this.format(date, {
      year: 'numeric',
      month: 'short',
      day: 'numeric',
      hour: '2-digit',
      minute: '2-digit'
    }, locale);
  }

  // Format long
  static formatLong(date: Date, locale: string = 'en-US'): string {
    return this.format(date, {
      weekday: 'long',
      year: 'numeric',
      month: 'long',
      day: 'numeric'
    }, locale);
  }
}

// 3. Custom Format Patterns
class CustomFormatter {
  // Format as YYYY-MM-DD
  static formatISODate(date: Date = new Date()): string {
    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}`;
  }

  // Format as HH:mm:ss
  static formatISOTime(date: Date = new Date()): string {
    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}`;
  }

  // Format as YYYY-MM-DD HH:mm:ss
  static formatISODateTime(date: Date = new Date()): string {
    return `${this.formatISODate(date)} ${this.formatISOTime(date)}`;
  }

  // Format as DD/MM/YYYY
  static formatDayMonthYear(date: Date = new Date(), separator: string = '/'): string {
    const day = String(date.getDate()).padStart(2, '0');
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const year = date.getFullYear();

    return `${day}${separator}${month}${separator}${year}`;
  }

  // Format as MM/DD/YYYY
  static formatMonthDayYear(date: Date = new Date(), separator: string = '/'): string {
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    const year = date.getFullYear();

    return `${month}${separator}${day}${separator}${year}`;
  }

  // Format with month name
  static formatWithMonthName(
    date: Date = new Date(),
    locale: string = 'en-US',
    format: 'short' | 'long' = 'long'
  ): string {
    const month = date.toLocaleString(locale, { month: format });
    const day = date.getDate();
    const year = date.getFullYear();

    return `${month} ${day}, ${year}`;
  }

  // Format with day and month names
  static formatWithDayAndMonthNames(
    date: Date = new Date(),
    locale: string = 'en-US'
  ): string {
    const weekday = date.toLocaleString(locale, { weekday: 'long' });
    const month = date.toLocaleString(locale, { month: 'long' });
    const day = date.getDate();
    const year = date.getFullYear();

    return `${weekday}, ${month} ${day}, ${year}`;
  }

  // Format time with AM/PM
  static formatTime12Hour(date: Date = new Date()): string {
    let hours = date.getHours();
    const minutes = String(date.getMinutes()).padStart(2, '0');
    const seconds = String(date.getSeconds()).padStart(2, '0');
    const ampm = hours >= 12 ? 'PM' : 'AM';

    hours = hours % 12;
    hours = hours ? hours : 12;

    return `${hours}:${minutes}:${seconds} ${ampm}`;
  }

  // Format time in 24-hour format
  static formatTime24Hour(date: Date = new Date()): string {
    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}`;
  }
}

// 4. Relative Time Formatting
class RelativeTimeFormatter {
  // Format time ago
  static formatTimeAgo(date: Date, locale: string = 'en-US'): string {
    const now = new Date();
    const diff = now.getTime() - 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);
    const months = Math.floor(days / 30);
    const years = Math.floor(days / 365);

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

    if (years > 0) {
      return rtf.format(-years, 'year');
    } else if (months > 0) {
      return rtf.format(-months, 'month');
    } else if (days > 0) {
      return rtf.format(-days, 'day');
    } else if (hours > 0) {
      return rtf.format(-hours, 'hour');
    } else if (minutes > 0) {
      return rtf.format(-minutes, 'minute');
    } else {
      return rtf.format(-seconds, 'second');
    }
  }

  // Format time in
  static formatTimeIn(date: Date, locale: string = 'en-US'): string {
    const now = new Date();
    const diff = date.getTime() - now.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);

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

    if (days > 0) {
      return rtf.format(days, 'day');
    } else if (hours > 0) {
      return rtf.format(hours, 'hour');
    } else if (minutes > 0) {
      return rtf.format(minutes, 'minute');
    } else {
      return rtf.format(seconds, 'second');
    }
  }

  // Format duration
  static formatDuration(milliseconds: number, locale: string = 'en-US'): string {
    const seconds = Math.floor(milliseconds / 1000);
    const minutes = Math.floor(seconds / 60);
    const hours = Math.floor(minutes / 60);
    const days = Math.floor(hours / 24);

    const parts: string[] = [];

    if (days > 0) {
      parts.push(`${days}d`);
    }
    if (hours % 24 > 0) {
      parts.push(`${hours % 24}h`);
    }
    if (minutes % 60 > 0) {
      parts.push(`${minutes % 60}m`);
    }
    if (seconds % 60 > 0 || parts.length === 0) {
      parts.push(`${seconds % 60}s`);
    }

    return parts.join(' ');
  }
}

// 5. Specialized Formatters
class SpecializedFormatter {
  // Format for file names
  static forFileName(date: Date = new Date()): string {
    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 `${year}${month}${day}_${hours}${minutes}${seconds}`;
  }

  // Format for log messages
  static forLog(date: Date = new Date()): string {
    return date.toISOString();
  }

  // Format for UI display
  static forDisplay(date: Date = new Date(), locale: string = 'en-US'): string {
    return date.toLocaleString(locale, {
      weekday: 'short',
      year: 'numeric',
      month: 'short',
      day: 'numeric',
      hour: '2-digit',
      minute: '2-digit'
    });
  }

  // Format for calendar
  static forCalendar(date: Date = new Date(), locale: string = 'en-US'): string {
    return date.toLocaleString(locale, {
      weekday: 'long',
      year: 'numeric',
      month: 'long',
      day: 'numeric'
    });
  }

  // Format for timestamp
  static forTimestamp(date: Date = new Date()): string {
    return String(date.getTime());
  }

  // Format for HTTP headers
  static forHTTPHeader(date: Date = new Date()): string {
    return date.toUTCString();
  }
}

// 6. Format Builder
class FormatBuilder {
  private parts: Array<string | number> = [];

  // Add year
  year(format: 'numeric' | '2-digit' = 'numeric'): this {
    this.parts.push(`YYYY${format === '2-digit' : 'YY'}`);
    return this;
  }

  // Add month
  month(format: 'numeric' | '2-digit' | 'short' | 'long' = 'numeric'): this {
    this.parts.push(`MM${format}`);
    return this;
  }

  // Add day
  day(format: 'numeric' | '2-digit' = 'numeric'): this {
    this.parts.push(`DD${format}`);
    return this;
  }

  // Add hour
  hour(format: 'numeric' | '2-digit' = '2-digit'): this {
    this.parts.push(`HH${format}`);
    return this;
  }

  // Add minute
  minute(format: 'numeric' | '2-digit' = '2-digit'): this {
    this.parts.push(`mm${format}`);
    return this;
  }

  // Add second
  second(format: 'numeric' | '2-digit' = '2-digit'): this {
    this.parts.push(`ss${format}`);
    return this;
  }

  // Add separator
  separator(sep: string): this {
    this.parts.push(sep);
    return this;
  }

  // Build format
  build(): (date: Date) => string {
    const pattern = this.parts.join('');
    return (date: Date) => {
      return pattern
        .replace(/YYYY/, String(date.getFullYear()))
        .replace(/YY/, String(date.getFullYear()).slice(-2))
        .replace(/MM2-digit/, String(date.getMonth() + 1).padStart(2, '0'))
        .replace(/MMnumeric/, String(date.getMonth() + 1))
        .replace(/DD2-digit/, String(date.getDate()).padStart(2, '0'))
        .replace(/DDnumeric/, String(date.getDate()))
        .replace(/HH2-digit/, String(date.getHours()).padStart(2, '0'))
        .replace(/HHnumeric/, String(date.getHours()))
        .replace(/mm2-digit/, String(date.getMinutes()).padStart(2, '0'))
        .replace(/mmnumeric/, String(date.getMinutes()))
        .replace(/ss2-digit/, String(date.getSeconds()).padStart(2, '0'))
        .replace(/ssnumeric/, String(date.getSeconds()));
    };
  }
}

// Usage Examples
async function demonstrateDateTimeFormatting() {
  console.log('=== Web TypeScript Date Time Formatting Examples ===\n');

  const date = new Date('2024-01-15T14:30:45Z');

  // 1. Basic formatting
  console.log('--- 1. Basic Formatting ---');
  console.log(`ISO string: ${BasicFormatter.toISOString(date)}`);
  console.log(`Locale string: ${BasicFormatter.toLocaleString(date)}`);
  console.log(`Locale date: ${BasicFormatter.toLocaleDateString(date)}`);
  console.log(`Locale time: ${BasicFormatter.toLocaleTimeString(date)}`);
  console.log(`UTC string: ${BasicFormatter.toUTCString(date)}`);

  // 2. Intl formatting
  console.log('\n--- 2. Intl Formatting ---');
  console.log(`Date only: ${IntlFormatter.formatDate(date)}`);
  console.log(`Time only: ${IntlFormatter.formatTime(date)}`);
  console.log(`Full: ${IntlFormatter.formatFull(date)}`);
  console.log(`Short: ${IntlFormatter.formatShort(date)}`);
  console.log(`Medium: ${IntlFormatter.formatMedium(date)}`);
  console.log(`Long: ${IntlFormatter.formatLong(date)}`);

  // 3. Custom formats
  console.log('\n--- 3. Custom Formats ---');
  console.log(`ISO date: ${CustomFormatter.formatISODate(date)}`);
  console.log(`ISO time: ${CustomFormatter.formatISOTime(date)}`);
  console.log(`ISO datetime: ${CustomFormatter.formatISODateTime(date)}`);
  console.log(`DD/MM/YYYY: ${CustomFormatter.formatDayMonthYear(date)}`);
  console.log(`MM/DD/YYYY: ${CustomFormatter.formatMonthDayYear(date)}`);
  console.log(`Month name: ${CustomFormatter.formatWithMonthName(date)}`);
  console.log(`With day/month names: ${CustomFormatter.formatWithDayAndMonthNames(date)}`);
  console.log(`12-hour time: ${CustomFormatter.formatTime12Hour(date)}`);
  console.log(`24-hour time: ${CustomFormatter.formatTime24Hour(date)}`);

  // 4. Relative time
  console.log('\n--- 4. Relative Time ---');
  const past = new Date();
  past.setMinutes(past.getMinutes() - 5);

  const future = new Date();
  future.setHours(future.getHours() + 2);

  console.log(`5 minutes ago: ${RelativeTimeFormatter.formatTimeAgo(past)}`);
  console.log(`2 hours in future: ${RelativeTimeFormatter.formatTimeIn(future)}`);
  console.log(`Duration (3665000ms): ${RelativeTimeFormatter.formatDuration(3665000)}`);

  // 5. Specialized formats
  console.log('\n--- 5. Specialized Formats ---');
  console.log(`File name: ${SpecializedFormatter.forFileName(date)}`);
  console.log(`Log: ${SpecializedFormatter.forLog(date)}`);
  console.log(`Display: ${SpecializedFormatter.forDisplay(date)}`);
  console.log(`Calendar: ${SpecializedFormatter.forCalendar(date)}`);
  console.log(`Timestamp: ${SpecializedFormatter.forTimestamp(date)}`);

  // 6. Format builder
  console.log('\n--- 6. Format Builder ---');
  const customFormat = new FormatBuilder()
    .year()
    .separator('-')
    .month('2-digit')
    .separator('-')
    .day('2-digit')
    .separator(' ')
    .hour('2-digit')
    .separator(':')
    .minute('2-digit')
    .separator(':')
    .second('2-digit')
    .build();

  console.log(`Custom format: ${customFormat(date)}`);

  // 7. Different locales
  console.log('\n--- 7. Different Locales ---');
  const locales = ['en-US', 'de-DE', 'fr-FR', 'ja-JP', 'zh-CN'];

  for (const locale of locales) {
    console.log(`${locale}: ${IntlFormatter.formatLong(date, locale)}`);
  }

  console.log('\n=== All Date Time Formatting Examples Completed ===');
}

// Export classes
export { BasicFormatter, IntlFormatter, CustomFormatter, RelativeTimeFormatter, SpecializedFormatter, FormatBuilder };
export { demonstrateDateTimeFormatting };

💻 Date Time Parsing typescript

🟡 intermediate ⭐⭐⭐

Parse strings into Date objects from various formats and validate date strings

⏱️ 30 min 🏷️ typescript, web, datetime, parsing
Prerequisites: Intermediate TypeScript, Date Parsing
// Web TypeScript Date Time Parsing Examples
// Parse strings into Date objects from various formats and validate date strings

// 1. Basic Parsing
class BasicParser {
  // Parse ISO string
  static parseISO(isoString: string): Date | null {
    const date = new Date(isoString);
    return isNaN(date.getTime()) ? null : date;
  }

  // Parse timestamp
  static parseTimestamp(timestamp: number): Date | null {
    const date = new Date(timestamp);
    return isNaN(date.getTime()) ? null : date;
  }

  // Parse date string (browser implementation)
  static parse(dateString: string): Date | null {
    const date = new Date(dateString);
    return isNaN(date.getTime()) ? null : date;
  }

  // Parse UTC string
  static parseUTC(utcString: string): Date | null {
    const date = new Date(utcString);
    return isNaN(date.getTime()) ? null : date;
  }
}

// 2. Custom Format Parsing
class CustomFormatParser {
  // Parse YYYY-MM-DD
  static parseISODate(dateString: string): Date | null {
    const match = dateString.match(/^(\d{4})-(\d{2})-(\d{2})$/);

    if (!match) {
      return null;
    }

    const [, year, month, day] = match;
    const date = new Date(`${year}-${month}-${day}T00:00:00Z`);

    return isNaN(date.getTime()) ? null : date;
  }

  // Parse DD/MM/YYYY or MM/DD/YYYY
  static parseDelimitedDate(
    dateString: string,
    format: 'DMY' | 'MDY' | 'YMD' = 'DMY'
  ): Date | null {
    const parts = dateString.split(/[\/\-]/);

    if (parts.length !== 3) {
      return null;
    }

    let [p1, p2, p3] = parts.map(p => parseInt(p));

    let year: number, month: number, day: number;

    if (format === 'DMY') {
      day = p1;
      month = p2;
      year = p3;
    } else if (format === 'MDY') {
      month = p1;
      day = p2;
      year = p3;
    } else {
      year = p1;
      month = p2;
      day = p3;
    }

    // Handle 2-digit years
    if (year < 100) {
      year += year < 50 ? 2000 : 1900;
    }

    const date = new Date(year, month - 1, day);

    if (date.getFullYear() !== year ||
        date.getMonth() !== month - 1 ||
        date.getDate() !== day) {
      return null;
    }

    return date;
  }

  // Parse time string HH:mm:ss
  static parseTime(timeString: string, baseDate: Date = new Date()): Date | null {
    const match = timeString.match(/^(\d{2}):(\d{2}):(\d{2})$/);

    if (!match) {
      return null;
    }

    const [, hours, minutes, seconds] = match.map(Number);
    const date = new Date(baseDate);

    date.setHours(hours, minutes, seconds, 0);

    return date;
  }

  // Parse date and time string
  static parseDateTime(dateTimeString: string): Date | null {
    // Try ISO format first
    if (dateTimeString.includes('T')) {
      return BasicParser.parseISO(dateTimeString);
    }

    // Try common formats
    const formats = [
      /^(\d{4})-(\d{2})-(\d{2}) (\d{2}):(\d{2}):(\d{2})$/,
      /^(\d{2})\/(\d{2})\/(\d{4}) (\d{2}):(\d{2}):(\d{2})$/
    ];

    for (const format of formats) {
      const match = dateTimeString.match(format);

      if (match) {
        const numbers = match.slice(1).map(Number);
        let date: Date;

        if (dateTimeString.includes('-')) {
          // YYYY-MM-DD HH:mm:ss
          date = new Date(numbers[0], numbers[1] - 1, numbers[2], numbers[3], numbers[4], numbers[5]);
        } else {
          // MM/DD/YYYY HH:mm:ss
          date = new Date(numbers[2], numbers[0] - 1, numbers[1], numbers[3], numbers[4], numbers[5]);
        }

        return isNaN(date.getTime()) ? null : date;
      }
    }

    return null;
  }
}

// 3. Natural Language Parsing
class NaturalLanguageParser {
  // Parse relative time strings like "in 5 minutes", "2 hours ago"
  static parseRelative(relativeString: string, baseDate: Date = new Date()): Date | null {
    const now = baseDate;
    const match = relativeString.match(/(in|ago)\s+(\d+)\s+(second|minute|hour|day|week|month|year)s?/i);

    if (!match) {
      return null;
    }

    const [, direction, amount, unit] = match;
    const value = parseInt(amount);

    let milliseconds = 0;

    switch (unit.toLowerCase()) {
      case 'second':
        milliseconds = value * 1000;
        break;
      case 'minute':
        milliseconds = value * 60 * 1000;
        break;
      case 'hour':
        milliseconds = value * 60 * 60 * 1000;
        break;
      case 'day':
        milliseconds = value * 24 * 60 * 60 * 1000;
        break;
      case 'week':
        milliseconds = value * 7 * 24 * 60 * 60 * 1000;
        break;
      case 'month':
        milliseconds = value * 30 * 24 * 60 * 60 * 1000;
        break;
      case 'year':
        milliseconds = value * 365 * 24 * 60 * 60 * 1000;
        break;
    }

    if (direction.toLowerCase() === 'in') {
      return new Date(now.getTime() + milliseconds);
    } else {
      return new Date(now.getTime() - milliseconds);
    }
  }

  // Parse "today", "tomorrow", "yesterday"
  static parseDay(dayString: string, baseDate: Date = new Date()): Date | null {
    const today = new Date(baseDate);
    today.setHours(0, 0, 0, 0);

    switch (dayString.toLowerCase()) {
      case 'today':
        return today;
      case 'tomorrow':
        return new Date(today.getTime() + 24 * 60 * 60 * 1000);
      case 'yesterday':
        return new Date(today.getTime() - 24 * 60 * 60 * 1000);
      default:
        return null;
    }
  }

  // Parse "next week", "last month"
  static parsePeriod(periodString: string, baseDate: Date = new Date()): Date | null {
    const match = periodString.match(/(next|last)\s+(week|month|year)/i);

    if (!match) {
      return null;
    }

    const [, direction, period] = match;
    const now = new Date(baseDate);

    if (period.toLowerCase() === 'week') {
      const days = direction.toLowerCase() === 'next' ? 7 : -7;
      return new Date(now.getTime() + days * 24 * 60 * 60 * 1000);
    } else if (period.toLowerCase() === 'month') {
      const months = direction.toLowerCase() === 'next' ? 1 : -1;
      return new Date(now.getFullYear(), now.getMonth() + months, now.getDate());
    } else if (period.toLowerCase() === 'year') {
      const years = direction.toLowerCase() === 'next' ? 1 : -1;
      return new Date(now.getFullYear() + years, now.getMonth(), now.getDate());
    }

    return null;
  }
}

// 4. Validation
class DateValidator {
  // Check if date string is valid
  static isValid(dateString: string): boolean {
    const date = new Date(dateString);
    return !isNaN(date.getTime());
  }

  // Validate ISO format
  static isValidISO(dateString: string): boolean {
    return /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d+)?(Z|[+-]\d{2}:\d{2})?$/.test(dateString);
  }

  // Validate date format YYYY-MM-DD
  static isValidISODate(dateString: string): boolean {
    if (!/^\d{4}-\d{2}-\d{2}$/.test(dateString)) {
      return false;
    }

    const date = new Date(dateString);
    return !isNaN(date.getTime());
  }

  // Validate time format HH:mm:ss
  static isValidTime(timeString: string): boolean {
    if (!/^\d{2}:\d{2}:\d{2}$/.test(timeString)) {
      return false;
    }

    const [hours, minutes, seconds] = timeString.split(':').map(Number);

    return hours >= 0 && hours <= 23 &&
           minutes >= 0 && minutes <= 59 &&
           seconds >= 0 && seconds <= 59;
  }

  // Validate email-style date
  static isValidEmailDate(dateString: string): boolean {
    return /^w{3},?s+d{1,2}s+w{3}s+d{4}s+d{2}:d{2}:d{2}s+[+-]?d{4}/.test(dateString);
  }
}

// 5. Format Detection
class FormatDetector {
  // Detect date format
  static detectFormat(dateString: string): string | null {
    if (/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}/.test(dateString)) {
      return 'ISO-8601';
    }

    if (/^\d{4}-\d{2}-\d{2}$/.test(dateString)) {
      return 'ISO-Date';
    }

    if (/^\d{2}\/\d{2}\/\d{4}$/.test(dateString)) {
      return 'Delimited';
    }

    if (/^\w{3},\s+\d{1,2}\s+\w{3}\s+\d{4}/.test(dateString)) {
      return 'HTTP-Date';
    }

    return null;
  }
}

// 6. Flexible Parser
class FlexibleParser {
  // Try multiple formats until one works
  static parse(dateString: string): Date | null {
    // Try built-in parsing first
    const builtin = BasicParser.parse(dateString);
    if (builtin) return builtin;

    // Try ISO date
    const isoDate = CustomFormatParser.parseISODate(dateString);
    if (isoDate) return isoDate;

    // Try delimited formats
    const dmy = CustomFormatParser.parseDelimitedDate(dateString, 'DMY');
    if (dmy) return dmy;

    const mdy = CustomFormatParser.parseDelimitedDate(dateString, 'MDY');
    if (mdy) return mdy;

    const ymd = CustomFormatParser.parseDelimitedDate(dateString, 'YMD');
    if (ymd) return ymd;

    // Try natural language
    const relative = NaturalLanguageParser.parseRelative(dateString);
    if (relative) return relative;

    const day = NaturalLanguageParser.parseDay(dateString);
    if (day) return day;

    return null;
  }

  // Parse with fallback
  static parseWithFallback(dateString: string, fallback: Date = new Date()): Date {
    const parsed = this.parse(dateString);
    return parsed || fallback;
  }
}

// 7. Timezone Parsing
class TimezoneParser {
  // Parse with timezone
  static parseWithTimezone(dateString: string, timezone: string): Date | null {
    try {
      const formatter = new Intl.DateTimeFormat('en-US', {
        timeZone: timezone,
        year: 'numeric',
        month: 'numeric',
        day: 'numeric',
        hour: 'numeric',
        minute: 'numeric',
        second: 'numeric'
      });

      const parts = formatter.formatToParts(new Date(dateString));
      const date: any = {};

      for (const part of parts) {
        if (part.type !== 'literal') {
          date[part.type] = part.value;
        }
      }

      return new Date(`${date.year}-${date.month}-${date.day}T${date.hour}:${date.minute}:${date.second}`);
    } catch {
      return null;
    }
  }
}

// Usage Examples
async function demonstrateDateTimeParsing() {
  console.log('=== Web TypeScript Date Time Parsing Examples ===\n');

  // 1. Basic parsing
  console.log('--- 1. Basic Parsing ---');
  console.log(`ISO string: ${BasicParser.parseISO('2024-01-15T10:30:00Z')}`);
  console.log(`Timestamp: ${BasicParser.parseTimestamp(1705318200000)}`);
  console.log(`Date string: ${BasicParser.parse('January 15, 2024')}`);
  console.log(`UTC string: ${BasicParser.parseUTC('Mon, 15 Jan 2024 10:30:00 GMT')}`);

  // 2. Custom format parsing
  console.log('\n--- 2. Custom Format Parsing ---');
  console.log(`ISO date: ${CustomFormatParser.parseISODate('2024-01-15')}`);
  console.log(`DD/MM/YYYY: ${CustomFormatParser.parseDelimitedDate('15/01/2024', 'DMY')}`);
  console.log(`MM/DD/YYYY: ${CustomFormatParser.parseDelimitedDate('01/15/2024', 'MDY')}`);
  console.log(`Time: ${CustomFormatParser.parseTime('14:30:45')}`);
  console.log(`DateTime: ${CustomFormatParser.parseDateTime('2024-01-15 14:30:45')}`);

  // 3. Natural language parsing
  console.log('\n--- 3. Natural Language Parsing ---');
  console.log(`"in 5 minutes": ${NaturalLanguageParser.parseRelative('in 5 minutes')}`);
  console.log(`"2 hours ago": ${NaturalLanguageParser.parseRelative('2 hours ago')}`);
  console.log(`"tomorrow": ${NaturalLanguageParser.parseDay('tomorrow')}`);
  console.log(`"yesterday": ${NaturalLanguageParser.parseDay('yesterday')}`);
  console.log(`"next week": ${NaturalLanguageParser.parsePeriod('next week')}`);
  console.log(`"last month": ${NaturalLanguageParser.parsePeriod('last month')}`);

  // 4. Validation
  console.log('\n--- 4. Validation ---');
  console.log(`"2024-01-15" is valid: ${DateValidator.isValid('2024-01-15')}`);
  console.log(`"2024-01-15T10:30:00Z" is valid ISO: ${DateValidator.isValidISO('2024-01-15T10:30:00Z')}`);
  console.log(`"2024-01-15" is valid ISO date: ${DateValidator.isValidISODate('2024-01-15')}`);
  console.log(`"14:30:45" is valid time: ${DateValidator.isValidTime('14:30:45')}`);
  console.log(`"25:61:61" is valid time: ${DateValidator.isValidTime('25:61:61')}`);

  // 5. Format detection
  console.log('\n--- 5. Format Detection ---');
  const formats = [
    '2024-01-15T10:30:00Z',
    '2024-01-15',
    '01/15/2024',
    'Mon, 15 Jan 2024 10:30:00 GMT'
  ];

  for (const format of formats) {
    console.log(`"${format}" => ${FormatDetector.detectFormat(format)}`);
  }

  // 6. Flexible parsing
  console.log('\n--- 6. Flexible Parsing ---');
  const inputs = [
    '2024-01-15',
    '15/01/2024',
    'January 15, 2024',
    'in 5 minutes',
    'tomorrow',
    'next week',
    'invalid date'
  ];

  for (const input of inputs) {
    const parsed = FlexibleParser.parse(input);
    console.log(`"${input}" => ${parsed || 'null'}`);
  }

  // 7. Parse with fallback
  console.log('\n--- 7. Parse with Fallback ---');
  const fallback = new Date('2020-01-01');
  console.log(`Valid date: ${FlexibleParser.parseWithFallback('2024-01-15', fallback)}`);
  console.log(`Invalid date (fallback): ${FlexibleParser.parseWithFallback('invalid', fallback)}`);

  console.log('\n=== All Date Time Parsing Examples Completed ===');
}

// Export classes
export { BasicParser, CustomFormatParser, NaturalLanguageParser, DateValidator, FormatDetector, FlexibleParser, TimezoneParser };
export { demonstrateDateTimeParsing };