[JavaScript] Có thể bạn đang sử dụng Date format sai cách

[JavaScript] Có thể bạn đang sử dụng Date format sai cách

Đức Huy

1 years 5 min read

Đa số ứng dụng web hiện tại khi nhận một một field time từ server response về sẽ dùng build in JS function để format lại thành date time dựa vào timezome của bạn bằng cách gọi hàm Date.toLocaleDateString(...)

Hàm Date.toLocaleDateString(...)

Date.toLocaleDateString(format?,options?) support format theo nhiều định dạng datetime:

const today = new Date()
const dotaFormattedNicely = today.toLocaleDateString('en-US', {
   month: 'long',
   weekday: 'long',
   day: 'numeric',
   year: 'numeric'
})
// "Saturday, March 16, 2024"

Bạn có thể tham khảo thêm các API khác ở đây.

Performance

Điều gì sẽ xảy ra khi bạn gọi function Date.toLocaleDateString()

  1. Khởi tạo DateTimeFormat object để xác định locale hiện tại và format theo tham số format. Bước này rất tốn time

  2. Sử dụng output của DateTimeFormat để format.

  3. Trả về kết quả format, giá trị DateTimeFormat sẽ bị clean bởi engine.

Sẽ không có gì nếu như trang web của bạn chỉ có một vài nơi cần format và hiển thị thời gian, việc bạn convert inline bằng cách gọi hàm Date.toLocaleDateString() sẽ chẳng có vấn đề gì, nhưng nếu trong một DataTable, List,... có tới hàng trăm, ngàn items, thì nó sẽ là một vấn đề lớn.

Thử một vài ví dụ:

const datesToFormat = [
    new Date("1775-04-18T00:00:00.000Z"),
    new Date("1775-04-19T00:00:00.000Z"),
    new Date("1775-04-20T00:00:00.000Z"),
    new Date("1775-04-21T00:00:00.000Z"),
    new Date("1775-04-22T00:00:00.000Z"),
];

for (const date of datesToFormat) {
    const formattedDateString = date.toLocaleDateString('en-US', {
        day: 'numeric',
        month: 'long',
        year: 'numeric'
    });

    // "April 19, 1775" ... "April 23, 1775"
    console.log(formattedDateString);
}

Hàm trên format time 5 lần, mỗi lần format như vậy nó gọi hàm date.toLocaleDateString truyền vào local string, mỗi lần gọi nó sẽ khởi tạo ại 1 object DateTimeFormat, như mình nói ở trên, bước này rất tốn thời gian.

Solution: Intl.DateTimeFormat

May mắn làm browsers cũng support khởi tạo Intl.DateTimeFormat một cách độc lập, điều đó có nghĩa là chúng ta có thể khởi tạo một object DateTimeFormat và tái sử dụng để format time.

// Expensive to create, but re-usable and only created once!
const formatter = new Intl.DateTimeFormat('en-US', {
    day: 'numeric',
    month: 'long',
    year: 'numeric'
});

const datesToFormat = [
    new Date("1775-04-18T00:00:00.000Z"),
    new Date("1775-04-19T00:00:00.000Z"),
    new Date("1775-04-20T00:00:00.000Z"),
    new Date("1775-04-21T00:00:00.000Z"),
    new Date("1775-04-22T00:00:00.000Z"),
];

for (const date of datesToFormat) {
    // This operation is very fast!
    const dateString = formatter.format(date);

    // "April 19, 1775" ... "April 23, 1775"
    console.log(dateString);
}

Profiled Example

Bạn có thể tham khảo live demo ở đây khi format 1000 dates.

Format 1000 Date items sử dụng toLocaleDateString() mất gần 217ms:

DateFormatting02.png

Cũng cùng một list dates đó khi format sử dụng Intl.DateTimeFormat chỉ mất khoảng 4ms:

DateFormatting03.png

Nguồn:

Source: https://webperf.tips/tip/date-formatting/

High level experience in web design and development knowledge, producing quality work.

© Nextlint_2023 All Rights Reserved

Privacy Policy Terms of Use