2020-03-26 13:51:24 +02:00
|
|
|
package utils
|
|
|
|
|
|
|
|
import (
|
|
|
|
"fmt"
|
|
|
|
"time"
|
|
|
|
)
|
|
|
|
|
2020-03-27 10:12:15 +02:00
|
|
|
func UnixToTimeAgo(timestamp int64) string {
|
2020-03-26 13:51:24 +02:00
|
|
|
now := time.Now().Unix()
|
2022-11-13 06:17:37 +02:00
|
|
|
return formatSecondsAgo(now - timestamp)
|
|
|
|
}
|
|
|
|
|
|
|
|
const (
|
|
|
|
SECONDS_IN_SECOND = 1
|
|
|
|
SECONDS_IN_MINUTE = 60
|
|
|
|
SECONDS_IN_HOUR = 3600
|
|
|
|
SECONDS_IN_DAY = 86400
|
|
|
|
SECONDS_IN_WEEK = 604800
|
|
|
|
SECONDS_IN_YEAR = 31536000
|
|
|
|
SECONDS_IN_MONTH = SECONDS_IN_YEAR / 12
|
|
|
|
)
|
|
|
|
|
|
|
|
type period struct {
|
|
|
|
label string
|
|
|
|
secondsInPeriod int64
|
|
|
|
}
|
|
|
|
|
|
|
|
var periods = []period{
|
|
|
|
{"s", SECONDS_IN_SECOND},
|
|
|
|
{"m", SECONDS_IN_MINUTE},
|
|
|
|
{"h", SECONDS_IN_HOUR},
|
|
|
|
{"d", SECONDS_IN_DAY},
|
|
|
|
{"w", SECONDS_IN_WEEK},
|
2023-07-16 12:09:07 +02:00
|
|
|
{"M", SECONDS_IN_MONTH},
|
2022-11-13 06:17:37 +02:00
|
|
|
{"y", SECONDS_IN_YEAR},
|
|
|
|
}
|
|
|
|
|
|
|
|
func formatSecondsAgo(secondsAgo int64) string {
|
|
|
|
for i, period := range periods {
|
|
|
|
if i == 0 {
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
|
|
|
|
if secondsAgo < period.secondsInPeriod {
|
|
|
|
return fmt.Sprintf("%d%s",
|
|
|
|
secondsAgo/periods[i-1].secondsInPeriod,
|
|
|
|
periods[i-1].label,
|
|
|
|
)
|
2020-03-26 13:51:24 +02:00
|
|
|
}
|
|
|
|
}
|
2022-11-13 06:17:37 +02:00
|
|
|
|
|
|
|
return fmt.Sprintf("%d%s",
|
|
|
|
secondsAgo/periods[len(periods)-1].secondsInPeriod,
|
|
|
|
periods[len(periods)-1].label,
|
|
|
|
)
|
2020-03-26 13:51:24 +02:00
|
|
|
}
|
2020-03-27 10:12:15 +02:00
|
|
|
|
2023-05-26 08:38:58 +02:00
|
|
|
// formats the date in a smart way, if the date is today, it will show the time, otherwise it will show the date
|
|
|
|
func UnixToDateSmart(now time.Time, timestamp int64, longTimeFormat string, shortTimeFormat string) string {
|
|
|
|
date := time.Unix(timestamp, 0)
|
|
|
|
|
|
|
|
if date.Day() == now.Day() && date.Month() == now.Month() && date.Year() == now.Year() {
|
|
|
|
return date.Format(shortTimeFormat)
|
|
|
|
}
|
|
|
|
|
|
|
|
return date.Format(longTimeFormat)
|
2020-03-27 10:12:15 +02:00
|
|
|
}
|