Tag Archive date

Byphunsanit

TypeScript: date-fns แทน Moment.js

ตอนแรกจะใช้ Moment.js ในการเปลี่ยนวันที่, เวลาที่แสดงให้เป็นรูปแบบตามภาษาที่ใช้ในแต่ละประเทศ ( locale ) แต่แล้วกลับเจอ Project Status โดยสรุปคือ ไม่ใช่มัน หรือไปใช้ date-fns แทน เลยต้องลองเปลี่ยนมาเป็นตัวนี้แทน

  1. ติดตั้งโดยใช้ command
    npm install date-fns
    npm install --save-dev @types/date-fns
  2. เพิ่มในไฟล์ app.ts
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    //date-fns
    const DATETIME_PATTERNS = 'yyyy-MM-dd HH:mm:ss';
     
    import { enUS as getLocale } from 'date-fns/locale';
    import { format } from 'date-fns';
    import { formatDistance } from 'date-fns/formatDistance';
    import { formatWithOptions } from 'date-fns/fp';
     
    window.DATETIME_PATTERNS = DATETIME_PATTERNS;
    window.format = format;
    window.formatDistance = formatDistance;
    window.formatWithOptions = formatWithOptions;
    window.getLocale = getLocale;
  3. สร้างไฟล์ date-fns.ts ในที่เดียวกับ app.ts
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    //date-fns
    import { format } from 'date-fns';
    import { formatWithOptions } from 'date-fns/fp';
    import * as locales from 'date-fns/locale'
    import formatDistance from 'date-fns/formatDistance';
    import formatRelative from 'date-fns/formatRelative';
    import subDays from 'date-fns/subDays';
     
    // Type for locale keys
    type DateFnsLocaleKey = keyof typeof locales
     
    // Common date patterns
    export const DATETIME_PATTERNS = {
        datetime: 'Pp',
        full: 'PPPPp',
        long: 'PPPP',
        medium: 'PP',
        short: 'P',
        time: 'p'
    } as const;
     
    // Helper function for date formatting
    export const formatDate = (
        date: Date | string,
        formatString: string,
        language: string
    ): string => {
        const dateObject = typeof date === 'string' ? new Date(date) : date
        return formatWithOptions(
            { locale: getLocale(language) },
            formatString
        )(dateObject)
    }
     
    // Function to get locale dynamically
    export const getLocale = (language: string) => {
        // Convert language code to match date-fns locale naming
        const localeKey = language === 'en' ? 'enUS' : language
     
        // Safely access locale
        const locale = locales[localeKey as DateFnsLocaleKey]
        return locale || locales.enUS // Fallback to English
    }
     
    /*
    const date = new Date();
    const formattedDate = formatDate(date, DATETIME_PATTERNS.full, 'th');
    console.log(formattedDate);
     
    const locale = getLocale('jp');
    console.log(locale);
    */
  4. ทดสอบโดย
    1
    2
    3
    4
    5
    6
    7
    8
    const currentDate = new Date();
     
    console.log('Date:', currentDate);
     
    // Format the date using the user's locale and a pattern
    const formattedDate = formatDate(currentDate, PATTERNS.full, userLanguage);
     
    console.log('Formatted Date:', formattedDate);
  5. และเปลี่ยนภาษาของ chrome ตามวิธี Change the language of your Chrome browser

ในส่วน DATETIME_PATTERNS จริง ๆ แล้วเป็นแค่การประกาศตัวแปรสำเร็จรูปไว้ สามารถให้ patterns ของตัวเองได้ โดยดูได้จาก format