Skip to content

Commit

Permalink
feat(i18n): add formatDate and formatIsoDate to i18n [KHCP-7929]
Browse files Browse the repository at this point in the history
  • Loading branch information
mptap committed Jul 18, 2023
1 parent 0c11020 commit 379f6b3
Showing 1 changed file with 39 additions and 0 deletions.
39 changes: 39 additions & 0 deletions packages/core/i18n/src/i18n.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,43 @@ export const createI18n = <MessageSource extends Record<string, any>>
intlCache,
)

/**
* Formats a unix timestamp into a formatted date string
* @param {Number} timestamp a unix timestamp in seconds
* @returns a date string formatted like 'Apr 6, 2022 10:50'
*/
const formatUnixTimeStamp = (timestamp: number): string => {
const invalidDate = 'Invalid Date'
if (!timestamp) {
return invalidDate
}

try {
const date = new Date(timestamp * 1000)

return intl.formatDate(date, {
year: 'numeric',
month: 'short',
day: 'numeric',
hour: 'numeric',
minute: 'numeric',
})
} catch (err) {
return invalidDate
}
}

/**
* Format an ISO fomatted date
* @param {String} isoDate ISO formatted date string
* @returns {String} date formatted like 'Apr 6, 2022 10:50'
*/
const formatIsoDate = (isoDate: string): string => {
const date = Date.parse(isoDate) / 1000

return formatUnixTimeStamp(date)
}

// Remove the native $t function from intlOriginal
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const { $t, ...otherProps } = intlOriginal
Expand All @@ -51,6 +88,8 @@ export const createI18n = <MessageSource extends Record<string, any>>
}

const localIntl: IntlShapeEx<MessageSource> = {
formatUnixTimeStamp,
formatIsoDate,
t,
te,
tm,
Expand Down

0 comments on commit 379f6b3

Please sign in to comment.