shell/time.go

100 lines
2.4 KiB
Go

package shell
import (
"fmt"
"strconv"
"strings"
"time"
"go.wit.com/log"
)
// converts a git for-each-ref date. "Wed Feb 7 10:13:38 2024 -0600"
func getGitDateStamp(gitdefault string) (time.Time, string, string) {
// now := time.Now().Format("Wed Feb 7 10:13:38 2024 -0600")
const gitLayout = "Mon Jan 2 15:04:05 2006 -0700"
tagTime, err := time.Parse(gitLayout, gitdefault)
if err != nil {
log.Warn("GOT THIS IN PARSE AAA." + gitdefault + ".AAA")
log.Warn(err)
return time.Now(), "Feb 1 12:34:56 1978 -0600", ""
}
return tagTime, gitdefault, GetDurationStamp(tagTime)
}
func getRawDateStamp(raw string) (time.Time, string, string) {
parts := strings.Split(raw, " ")
if len(parts) == 0 {
// raw was blank here
// return "Jan 4 1977", "40y" // eh, why not. it'll be easy to grep for this
return time.Now(), "Jan 4 1977", "40y" // eh, why not. it'll be easy to grep for this
}
i, err := strconv.ParseInt(parts[0], 10, 64) // base 10 string, return int64
if err != nil {
log.Warn("Error converting timestamp:", raw)
log.Warn("Error converting timestamp err =", err)
return time.Now(), "", ""
}
// Parse the Unix timestamp into a time.Time object
gitTagDate := time.Unix(i, 0)
return gitTagDate, gitTagDate.UTC().Format("2006/01/02 15:04:05 UTC"), GetDurationStamp(gitTagDate)
}
func GetDurationStamp(t time.Time) string {
// Get the current time
currentTime := time.Now()
// Calculate the duration between t current time
duration := currentTime.Sub(t)
return FormatDuration(duration)
}
func FormatDuration(d time.Duration) string {
result := ""
// check if it's more than a year
years := int(d.Hours()) / (24 * 365)
if years > 0 {
result += fmt.Sprintf("%dy ", years)
return result
}
// check if it's more than a day
days := int(d.Hours()) / 24
if days > 0 {
result += fmt.Sprintf("%dd ", days)
return result
}
// check if it's more than an hour
hours := int(d.Hours()) % 24
if hours > 0 {
result += fmt.Sprintf("%dh ", hours)
return result
}
// check if it's more than a minute
minutes := int(d.Minutes()) % 60
if minutes > 0 {
result += fmt.Sprintf("%dm ", minutes)
return result
}
// check if it's more than a second
seconds := int(d.Seconds()) % 60
if seconds > 0 {
result += fmt.Sprintf("%ds", seconds)
return result
}
// report in milliseconds
ms := int(d.Milliseconds())
if ms > 100 {
// todo: print .3s, etc ?
}
result += fmt.Sprintf("%dms", ms)
return result
}