Elysia Tools

在一个清晰的工作台里浏览工具、案例、可视化和主题指南。

热门分类

专题

语言
ZHDERUPTENFRES

Elysia Tools

导航

TypeScript

Web TypeScript 日期时间示例

Web TypeScript 日期和时间示例,包括获取当前时间、格式化、解析和操作

案例

这个案例集合中的条目

代码typescript简单

获取当前时间

使用Date API以各种格式和时区检索当前日期和时间

难度

3/10

预计时间

15 min

标签

typescript, web, datetime

前置条件

Basic TypeScript, Date API

typescript
// 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 };
代码typescript中等

日期时间格式化

使用Intl API和自定义格式化程序将日期和时间格式化为各种字符串表示形式

难度

5/10

预计时间

25 min

标签

typescript, web, datetime, formatting

前置条件

Intermediate TypeScript, Intl API

typescript
// 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 };
代码typescript中等

日期时间解析

将各种格式的字符串解析为Date对象并验证日期字符串

难度

6/10

预计时间

30 min

标签

typescript, web, datetime, parsing

前置条件

Intermediate TypeScript, Date Parsing

typescript
// 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 };

工具

经常与该案例搭配使用的工具

相关内容

相关案例集合

相关内容

相关专题

专题

获授权 Webhook 捕获与接收端信任检查

在获授权的测试环境捕获并回放受控 Webhook 请求,分别检查投递证据和接收端 HTTPS 证书,不把证书有效误写成业务信任证明。

专题

用日志、链路、Webhook 和 JSON 载荷做可观测性调试

解析日志,解码调用链,检查 Webhook/API 证据,探索 JSON 载荷,并提取重复模式,形成可用于事故复盘的调试结论。

专题

视频交付格式转换:音频、媒体流、GIF、WebM 与 MP4

先按交付场景选择视频或动画格式,再提取所需的音频或视频流,并记录转换后的兼容性、质量和体积取舍。

专题

日期时间标准化与截止日计算

把含糊或混合格式的日期时间输入整理为经过校验、具备时区语义、可直接执行的时间戳、标准时间和业务截止日结果。

首页
工具3212
案例593
可视化471
文件查看器103
专题239
标签333
图像、音频与视频657

图像、音频、视频处理、转换与优化工具

数学、日期与金融647

计算器、数值计算、日期逻辑、统计与金融工具

设计与颜色298

颜色、版式、图形、视觉样式与设计辅助工具

文本与写作209

写作、清洗、格式化、提取与文本分析工具

开发与 Web193

开发者工具、网络处理、Web 调试与自动化辅助工具

转换与编码175

格式、文件、压缩包、单位与编码转换工具

潜客测验发布与联系人交接
讣告、悼词与纪念卡的家属复核及交付
本地习惯记录的备份、恢复演练与分享前检查
长文改编 X 串文与 LinkedIn 帖子的事实复核与交付
Markdown 互动课件审校、离线演示与交付

© 2026 Elysia Tools. 保留所有权利。

文档价格关于我们服务条款隐私政策Cookie 政策联系我们

Validation

日期时间校验器

验证日期时间格式,包括ISO8601、自定义格式、闰年和月份/日期验证

Format Conversion

日期格式化器

将日期字符串转换为各种格式的日期格式

Text Processing

日期提取器

从文本中提取多种格式的日期,包括中文、ISO和美国格式,提供详细分析和摘要

Utilities

文本日期格式统一器

在文本内容中查找并统一日期格式

Utilities

日期格式统一器

将各种日期格式转换为统一格式

Date & Time

时长格式化器

将时长格式化为各种人类可读格式

Utilities

日期加法器

从日期添加或减去时间段(年、月、日、时、分、秒)

Utilities

日期差异计算器

计算两个日期之间的差异,以多种时间单位表示

TypeScript

Web TypeScript 字符串处理示例

Web TypeScript 字符串处理示例,包括字符串操作、模式匹配和文本转换

Swift

macOS Swift 日期时间示例

macOS Swift 日期时间示例,包括获取当前时间、时间格式化和时间解析

Go

Web Go 日期时间示例

Web Go 日期时间示例,包括获取当前时间、格式化、解析和时区操作

Python

Web Python 日期时间示例

Web Python 日期时间示例,包括获取当前时间、格式化、解析和时区操作

C++

Windows 日期时间 - C++ 示例

Windows平台C++日期时间示例,包括时间获取、格式化和解析操作

TypeScript

Web TypeScript 文件操作示例

Web TypeScript 文件操作示例,包括文本文件读写、文件复制移动、目录遍历和文件验证