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
|
|
|
|
)
|
|
|
|
|
2020-06-13 07:29:32 +00:00
|
|
|
type truncator struct {
|
2020-05-26 06:51:06 +00:00
|
|
|
d time.Duration
|
|
|
|
s string
|
2020-06-13 07:29:32 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
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)
|
2020-06-13 07:29:32 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
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()
|
2020-06-13 07:29:32 +00:00
|
|
|
ensureLocale()
|
|
|
|
|
|
|
|
trunc := t
|
2020-06-29 02:55:13 +00:00
|
|
|
now := time.Now().Local()
|
2020-06-13 07:29:32 +00:00
|
|
|
|
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 ""
|
|
|
|
}
|