From 5b32ed3e337fa0e33929c50dfabc0cda0dec1b80 Mon Sep 17 00:00:00 2001 From: Virgil Date: Wed, 1 Apr 2026 22:57:55 +0000 Subject: [PATCH] feat(time): add month and year relative formatting Co-Authored-By: Virgil --- time.go | 6 +++++- time_test.go | 10 ++++++++++ 2 files changed, 15 insertions(+), 1 deletion(-) diff --git a/time.go b/time.go index cc48821..42a767d 100644 --- a/time.go +++ b/time.go @@ -26,8 +26,12 @@ func TimeAgo(t time.Time) string { return FormatAgo(int(duration.Hours()), "hour") case duration < 7*24*time.Hour: return FormatAgo(int(duration.Hours()/24), "day") - default: + case duration < 30*24*time.Hour: return FormatAgo(int(duration.Hours()/(24*7)), "week") + case duration < 365*24*time.Hour: + return FormatAgo(int(duration.Hours()/(24*30)), "month") + default: + return FormatAgo(int(duration.Hours()/(24*365)), "year") } } diff --git a/time_test.go b/time_test.go index c1ed096..5d055f6 100644 --- a/time_test.go +++ b/time_test.go @@ -26,6 +26,8 @@ func TestTimeAgo_Good(t *testing.T) { {"hours_ago", 3 * time.Hour, "3 hours ago"}, {"days_ago", 2 * 24 * time.Hour, "2 days ago"}, {"weeks_ago", 3 * 7 * 24 * time.Hour, "3 weeks ago"}, + {"months_ago", 40 * 24 * time.Hour, "1 month ago"}, + {"years_ago", 400 * 24 * time.Hour, "1 year ago"}, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { @@ -59,6 +61,14 @@ func TestTimeAgo_Good_EdgeCases(t *testing.T) { // Just under 1 week got = TimeAgo(time.Now().Add(-6 * 24 * time.Hour)) assert.Contains(t, got, "days ago") + + // Just over 4 weeks + got = TimeAgo(time.Now().Add(-31 * 24 * time.Hour)) + assert.Contains(t, got, "month ago") + + // Well over a year + got = TimeAgo(time.Now().Add(-800 * 24 * time.Hour)) + assert.Contains(t, got, "years ago") } func TestTimeAgo_Good_SingleUnits(t *testing.T) {