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" * - Returns empty string for future dates. * */ export function getTimeAgoText(checkoutDate: string, intl: IntlShape): string { const now = dt() const checkout = dt(checkoutDate) const daysDiff = now.diff(checkout, "days") // Return empty string for future dates if (daysDiff < 0) { return "" } 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 } ) }