From e28a86d705aed5315b7db25414f11e21e86db00a Mon Sep 17 00:00:00 2001 From: Virgil Date: Thu, 2 Apr 2026 08:41:07 +0000 Subject: [PATCH] feat(time): use locale word fallback for relative time Co-Authored-By: Virgil --- time.go | 11 ++++++++++- time_test.go | 25 +++++++++++++++++++++++++ 2 files changed, 35 insertions(+), 1 deletion(-) diff --git a/time.go b/time.go index 6d430b2..d01efa5 100644 --- a/time.go +++ b/time.go @@ -48,11 +48,20 @@ func FormatAgo(count int, unit string) string { key := "time.ago." + unit result := svc.T(key, map[string]any{"Count": count}) if result == key { - return core.Sprintf("%d %s ago", count, Pluralize(unit, count)) + return core.Sprintf("%d %s ago", count, fallbackAgoUnit(unit, count)) } return result } +func fallbackAgoUnit(unit string, count int) string { + lang := currentLangForGrammar() + rendered := renderWord(lang, unit) + if rendered != unit { + return rendered + } + return Pluralize(unit, count) +} + func normalizeAgoUnit(unit string) string { unit = core.Lower(core.Trim(unit)) switch unit { diff --git a/time_test.go b/time_test.go index e8b7db5..41a8595 100644 --- a/time_test.go +++ b/time_test.go @@ -245,3 +245,28 @@ func TestFormatAgo_Good_FrenchRelativeTime(t *testing.T) { }) } } + +func TestFormatAgo_FallsBackToLocaleWordMap(t *testing.T) { + prev := Default() + svc, err := NewWithFS(fstest.MapFS{ + "en.json": &fstest.MapFile{ + Data: []byte(`{ + "gram": { + "word": { + "month": "mois" + } + } + }`), + }, + }, ".") + require.NoError(t, err) + SetDefault(svc) + t.Cleanup(func() { + SetDefault(prev) + }) + + require.NoError(t, SetLanguage("en")) + + got := FormatAgo(2, "month") + assert.Equal(t, "2 mois ago", got) +}