commit 00af87d7ff655867d5923818c7c4bea943e7e925
parent ccc558d5e81deeaef76a1f1fb268f43b523eccf7
Author: alex wennerberg <alex@alexwennerberg.com>
Date: Sun, 31 Dec 2023 12:32:19 -0500
Add relative date time formatting
Diffstat:
2 files changed, 31 insertions(+), 0 deletions(-)
diff --git a/server/server.go b/server/server.go
@@ -180,6 +180,7 @@ func generateTemplates(config types.Config, translator i18n.Translator) (*templa
"formatDate": func(t time.Time) string {
return t.Format("2006-01-02")
},
+ "formatDateTimeRelative": util.RelativeTime,
"formatDateRelative": func(t time.Time) string {
diff := time.Since(t)
if diff < time.Hour*24 {
diff --git a/util/util.go b/util/util.go
@@ -17,6 +17,7 @@ import (
"regexp"
"strconv"
"strings"
+ "time"
"github.com/gomarkdown/markdown"
"github.com/komkom/toml"
@@ -182,6 +183,35 @@ func CreateIfNotExist(docpath, content string) (bool, error) {
return false, nil
}
+const solarYearSecs = 31556926
+
+func RelativeTime(t time.Time) string {
+ d := time.Since(t)
+ var metric string
+ var amount int
+ if d.Seconds() < 60 {
+ amount = int(d.Seconds())
+ metric = "second"
+ } else if d.Minutes() < 60 {
+ amount = int(d.Minutes())
+ metric = "minute"
+ } else if d.Hours() < 24 {
+ amount = int(d.Hours())
+ metric = "hour"
+ } else if d.Seconds() < solarYearSecs {
+ amount = int(d.Hours()) / 24
+ metric = "day"
+ } else {
+ amount = int(d.Seconds()) / solarYearSecs
+ metric = "year"
+ }
+ if amount == 1 {
+ return fmt.Sprintf("%d %s ago", amount, metric)
+ } else {
+ return fmt.Sprintf("%d %ss ago", amount, metric)
+ }
+}
+
func ReadConfig(confpath string) types.Config {
ed := Describe("config")
_, err := CreateIfNotExist(confpath, defaults.DEFAULT_CONFIG)