2023-07-18 16:09:45 +00:00
|
|
|
package format
|
|
|
|
|
|
|
|
import (
|
|
|
|
"fmt"
|
|
|
|
"math"
|
|
|
|
"strings"
|
|
|
|
"time"
|
|
|
|
)
|
|
|
|
|
2023-10-11 18:05:39 +00:00
|
|
|
// humanDuration returns a human-readable approximation of a
|
|
|
|
// duration (eg. "About a minute", "4 hours ago", etc.).
|
|
|
|
func humanDuration(d time.Duration) string {
|
2023-07-18 16:09:45 +00:00
|
|
|
seconds := int(d.Seconds())
|
|
|
|
|
|
|
|
switch {
|
|
|
|
case seconds < 1:
|
2023-10-11 18:05:39 +00:00
|
|
|
return "Less than a second"
|
2023-07-18 16:09:45 +00:00
|
|
|
case seconds == 1:
|
|
|
|
return "1 second"
|
|
|
|
case seconds < 60:
|
|
|
|
return fmt.Sprintf("%d seconds", seconds)
|
|
|
|
}
|
|
|
|
|
|
|
|
minutes := int(d.Minutes())
|
|
|
|
switch {
|
|
|
|
case minutes == 1:
|
2023-10-11 18:05:39 +00:00
|
|
|
return "About a minute"
|
2023-07-18 16:09:45 +00:00
|
|
|
case minutes < 60:
|
|
|
|
return fmt.Sprintf("%d minutes", minutes)
|
|
|
|
}
|
|
|
|
|
|
|
|
hours := int(math.Round(d.Hours()))
|
|
|
|
switch {
|
|
|
|
case hours == 1:
|
2023-10-11 18:05:39 +00:00
|
|
|
return "About an hour"
|
2023-07-18 16:09:45 +00:00
|
|
|
case hours < 48:
|
|
|
|
return fmt.Sprintf("%d hours", hours)
|
|
|
|
case hours < 24*7*2:
|
|
|
|
return fmt.Sprintf("%d days", hours/24)
|
|
|
|
case hours < 24*30*2:
|
|
|
|
return fmt.Sprintf("%d weeks", hours/24/7)
|
|
|
|
case hours < 24*365*2:
|
|
|
|
return fmt.Sprintf("%d months", hours/24/30)
|
|
|
|
}
|
|
|
|
|
|
|
|
return fmt.Sprintf("%d years", int(d.Hours())/24/365)
|
|
|
|
}
|
|
|
|
|
|
|
|
func HumanTime(t time.Time, zeroValue string) string {
|
2023-10-11 18:05:39 +00:00
|
|
|
return humanTime(t, zeroValue)
|
2023-07-18 16:09:45 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
func HumanTimeLower(t time.Time, zeroValue string) string {
|
2023-10-11 18:05:39 +00:00
|
|
|
return strings.ToLower(humanTime(t, zeroValue))
|
2023-07-18 16:09:45 +00:00
|
|
|
}
|
|
|
|
|
2023-10-11 18:05:39 +00:00
|
|
|
func humanTime(t time.Time, zeroValue string) string {
|
2023-07-18 16:09:45 +00:00
|
|
|
if t.IsZero() {
|
|
|
|
return zeroValue
|
|
|
|
}
|
|
|
|
|
|
|
|
delta := time.Since(t)
|
|
|
|
if delta < 0 {
|
2023-10-11 18:05:39 +00:00
|
|
|
return humanDuration(-delta) + " from now"
|
2023-07-18 16:09:45 +00:00
|
|
|
}
|
|
|
|
|
2023-10-11 18:05:39 +00:00
|
|
|
return humanDuration(delta) + " ago"
|
2023-07-18 16:09:45 +00:00
|
|
|
}
|