Files
web/apps/scandic-web/utils/getRelativePastTime.ts
Chuma Mcphoy (We Ahead) ac5fdc64a9 Merged in feat/LOY-428-previous-stay-redesign (pull request #3142)
Feat(LOY-428): Previous Stays Redesign

* feat(LOY-428): Previous stays WIP

* fix(LOY-428): fix alignment issue

* fix(LOY-428): css fixes & imagefallback prop value

* fix(LOY-428): use css vars

* fix(LOY-428): add unit test for relative time text

* chore(LOY-428): remove else if conditions

* fix(LOY-428): named exports & remove duplicate width/height setting

* fix(LOY-428): better formatting of upcoming stays months text

* fix(LOY-428): fewer typography wrappers


Approved-by: Matilda Landström
2025-11-19 12:08:34 +00:00

55 lines
1.4 KiB
TypeScript

import { dt } from "@scandic-hotels/common/dt"
import type { IntlShape } from "react-intl"
/**
* Returns relative past time text for a date (e.g., "3 days ago", "2 months ago", "1 year ago")
*
* Examples:
* - 1-30 days: "1 day ago", "15 days ago", "30 days ago"
* - 31-364 days: "1 month ago", "6 months ago", "12 months ago"
* - 365+ days: "1 year ago", "2 years ago", "5 years ago"
*/
export function getRelativePastTime(
checkoutDate: string,
intl: IntlShape
): string {
const now = dt()
const checkout = dt(checkoutDate)
const daysDiff = now.diff(checkout, "days")
if (daysDiff <= 30) {
// 1-30 days
return intl.formatMessage(
{
id: "common.nrDaysAgo",
defaultMessage: "{count, plural, one {# day ago} other {# days ago}}",
},
{ count: daysDiff }
)
}
if (daysDiff <= 364) {
// 31-364 days (show months)
const monthsDiff = Math.floor(daysDiff / 30)
return intl.formatMessage(
{
id: "common.nrMonthsAgo",
defaultMessage:
"{count, plural, one {# month ago} other {# months ago}}",
},
{ count: monthsDiff }
)
}
// 365+ days (show years)
const yearsDiff = Math.floor(daysDiff / 365)
return intl.formatMessage(
{
id: "common.nrYearsAgo",
defaultMessage: "{count, plural, one {# year ago} other {# years ago}}",
},
{ count: yearsDiff }
)
}