goext/timeext/duration.go
Mike Schwörer 98c591b019
All checks were successful
Build Docker and Deploy / Run goext test-suite (push) Successful in 3m7s
v0.0.577
2025-05-18 21:42:18 +02:00

98 lines
2.5 KiB
Go

package timeext
import (
"fmt"
"git.blackforestbytes.com/BlackForestBytes/goext/langext"
"time"
)
func FromNanoseconds[T langext.NumberConstraint](v T) time.Duration {
return time.Duration(int64(float64(v) * float64(time.Nanosecond)))
}
func FromMicroseconds[T langext.NumberConstraint](v T) time.Duration {
return time.Duration(int64(float64(v) * float64(time.Microsecond)))
}
func FromMilliseconds[T langext.NumberConstraint](v T) time.Duration {
return time.Duration(int64(float64(v) * float64(time.Millisecond)))
}
func FromSeconds[T langext.NumberConstraint](v T) time.Duration {
return time.Duration(int64(float64(v) * float64(time.Second)))
}
func FromMinutes[T langext.NumberConstraint](v T) time.Duration {
return time.Duration(int64(float64(v) * float64(time.Minute)))
}
func FromHours[T langext.NumberConstraint](v T) time.Duration {
return time.Duration(int64(float64(v) * float64(time.Hour)))
}
func FromDays[T langext.NumberConstraint](v T) time.Duration {
return time.Duration(int64(float64(v) * float64(24) * float64(time.Hour)))
}
func FormatNaturalDurationEnglish(iv time.Duration) string {
if sec := int64(iv.Seconds()); sec < 180 {
if sec == 1 {
return "1 second ago"
} else {
return fmt.Sprintf("%d seconds ago", sec)
}
}
if mins := int64(iv.Minutes()); mins < 180 {
return fmt.Sprintf("%d minutes ago", mins)
}
if hours := int64(iv.Hours()); hours < 72 {
return fmt.Sprintf("%d hours ago", hours)
}
if days := int64(iv.Hours() / 24.0); days < 21 {
return fmt.Sprintf("%d days ago", days)
}
if weeks := int64(iv.Hours() / 24.0 / 7.0); weeks < 12 {
return fmt.Sprintf("%d weeks ago", weeks)
}
if months := int64(iv.Hours() / 24.0 / 7.0 / 30); months < 36 {
return fmt.Sprintf("%d months ago", months)
}
years := int64(iv.Hours() / 24.0 / 7.0 / 365)
return fmt.Sprintf("%d years ago", years)
}
func FormatDurationGerman(iv time.Duration) string {
if sec := int64(iv.Seconds()); sec < 180 {
return fmt.Sprintf("%ds", sec)
}
if mins := int64(iv.Minutes()); mins < 180 {
return fmt.Sprintf("%dmin", mins)
}
if hours := int64(iv.Hours()); hours < 72 {
return fmt.Sprintf("%dh", hours)
}
if days := int64(iv.Hours() / 24.0); days < 21 {
return fmt.Sprintf("%d Tage", days)
}
if weeks := int64(iv.Hours() / 24.0 / 7.0); weeks < 12 {
return fmt.Sprintf("%d Wochen", weeks)
}
if months := int64(iv.Hours() / 24.0 / 7.0 / 30); months < 36 {
return fmt.Sprintf("%d Monate", months)
}
years := int64(iv.Hours() / 24.0 / 7.0 / 365)
return fmt.Sprintf("%d Jahre", years)
}