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 {
|
|
|
|
ensureLocale()
|
|
|
|
|
|
|
|
trunc := t
|
|
|
|
now := time.Now()
|
|
|
|
|
2020-06-13 07:29:32 +00:00
|
|
|
for _, truncator := range shortTruncators {
|
|
|
|
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 ""
|
|
|
|
}
|
|
|
|
|
|
|
|
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 {
|
|
|
|
ensureLocale()
|
|
|
|
|
|
|
|
trunc := t
|
|
|
|
now := time.Now()
|
|
|
|
|
|
|
|
for _, truncator := range longTruncators {
|
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 ""
|
|
|
|
}
|