1
0
Fork 0
mirror of https://github.com/diamondburned/cchat-gtk.git synced 2024-11-16 03:02:45 +00:00
cchat-gtk/internal/humanize/humanize.go

64 lines
1.1 KiB
Go
Raw Normal View History

2020-05-26 06:51:06 +00:00
package humanize
import (
"time"
"github.com/goodsign/monday"
)
const (
Day = 24 * time.Hour
Week = 7 * Day
Year = 365 * Day
)
type truncator struct {
2020-05-26 06:51:06 +00:00
d time.Duration
s string
}
var shortTruncators = []truncator{
2020-05-26 06:51:06 +00:00
{d: Day, s: "15:04"},
{d: Week, s: "Mon 15:04"},
{d: Year, s: "15:04 02/01"},
{d: -1, s: "15:04 02/01/2006"},
}
func TimeAgo(t time.Time) string {
2020-06-28 23:01:08 +00:00
return timeAgo(t, shortTruncators)
}
var longTruncators = []truncator{
{d: Day, s: "Today at 15:04"},
{d: Week, s: "Last Monday at 15:04"},
{d: -1, s: "15:04 02/01/2006"},
}
func TimeAgoLong(t time.Time) string {
2020-06-28 23:01:08 +00:00
return timeAgo(t, longTruncators)
}
func TimeAgoShort(t time.Time) string {
2020-06-29 02:55:13 +00:00
t = t.Local()
2020-06-28 23:01:08 +00:00
return monday.Format(t, "15:04", Locale)
}
func timeAgo(t time.Time, truncs []truncator) string {
2020-06-29 02:55:13 +00:00
t = t.Local()
ensureLocale()
trunc := t
2020-06-29 02:55:13 +00:00
now := time.Now().Local()
2020-06-28 23:01:08 +00:00
for _, truncator := range truncs {
2020-05-26 06:51:06 +00:00
trunc = trunc.Truncate(truncator.d)
now = now.Truncate(truncator.d)
if trunc.Equal(now) || truncator.d == -1 {
return monday.Format(t, truncator.s, Locale)
}
}
return ""
}