feat(time): use locale word fallback for relative time

Co-Authored-By: Virgil <virgil@lethean.io>
This commit is contained in:
Virgil 2026-04-02 08:41:07 +00:00
parent 8a23f26a47
commit e28a86d705
2 changed files with 35 additions and 1 deletions

11
time.go
View file

@ -48,11 +48,20 @@ func FormatAgo(count int, unit string) string {
key := "time.ago." + unit key := "time.ago." + unit
result := svc.T(key, map[string]any{"Count": count}) result := svc.T(key, map[string]any{"Count": count})
if result == key { 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 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 { func normalizeAgoUnit(unit string) string {
unit = core.Lower(core.Trim(unit)) unit = core.Lower(core.Trim(unit))
switch unit { switch unit {

View file

@ -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)
}