Tag Archive date-fns

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
    //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
    //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
    // https://date-fns.org/v4.1.0/docs/format
    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. ทดสอบโดย
    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