Skip to main content

Date and Time

We provide you with the formatDateTime function to format a date based on the active language. The active language is retrieved from the language tag attribute on AppContext, which is obtained from the route prefix.

For example, if the route prefix is en-id then the language tag is en-ID.

The formatDateTime util

Parameters

This util accepts the following parameters:

  • date — A Date object to be formatted.
  • options — A DateTimeFormatOptions object that contains the formatting options.
    • pattern — A string that specifies the desired date and time format.

Available formatters

The function uses two main date-and-time formatters:

warning

If options.pattern is not provided, the legacy date and time formatting logic is used. This is to ensure backward compatibility with the existing implementations. IT WILL BE DEPRECATED SOON! It is recommended to use the new logic.

The formatter depends on the language tag provided in the AppContext. The default formatter used in date-fns is enUS. If a new language is introduced, please update the DATE_LOCALE_FNS_MAP constant to include the new language.

The formatter will format the provided Date object into a string specified on the options.pattern parameter (and throw an error if you try to specify an unregistered pattern):

// See the SSOT document for more information
export enum DateTimePatternOptionsEnum {
'dd-MM-yyyy' = 'dd-MM-yyyy',
'dd/MM/yyyy' = 'dd/MM/yyyy',
'yyyy-MM-dd' = 'yyyy-MM-dd',
'yyyy.MM.dd' = 'yyyy.MM.dd',
'dd MMM yyyy' = 'dd MMM yyyy',
'EEEE, d MMM yyyy' = 'EEEE, d MMM yyyy',
'EE, d MMM yyyy' = 'EE, d MMM yyyy',
'EE, d MMM' = 'EE, d MMM',
'EE, d MMM yy' = 'EE, d MMM yy',
"yyyy-MM-dd'T'HH:mm:ss'Z'" = "yyyy-MM-dd'T'HH:mm:ss'Z'",
'd MMM yyyy, hh:mm a' = 'd MMM yyyy, hh:mm a',
'd MMM yyyy' = 'd MMM yyyy',
'd MMMM yyyy' = 'd MMMM yyyy',
'd MMM' = 'd MMM',
'd MMMM' = 'd MMMM',
'MMM yyyy' = 'MMM yyyy',
'MMMM yyyy' = 'MMMM yyyy',
'MMM' = 'MMM',
'MMMM' = 'MMMM',
'EEEE' = 'EEEE',
'HH:mm' = 'HH:mm',
'EEE' = 'EEE',
}

The expected Output

The formatted date will be based on the Single Source of Truth (SSOT) documentation.

The SSOT documentation outlines the standardized date-and-time formats for each language and region. The formatDateTime function will use these formats to ensure consistency and accuracy in date and time formatting.

The useDateFormatter hook

This hook is a wrapper around the formatDateTime function that provides the active language from the AppContext. It allows you to easily format dates in your components without having to manually retrieve the active language.

import { useDateFormatter } from '@traveloka/core';
function MyComponent() {
const formatDateTime = useDateFormatter();

const formattedDate = formatDateTime(new Date(), { pattern: 'dd MMM yyyy' });

return <div>{formattedDate}</div>;
}

[!Warning] This hook is only available in the client-side environment. On the server-side, it will return an empty string.