worklog/internal/tools/datetime.go

117 lines
2.3 KiB
Go
Raw Normal View History

2023-01-27 17:09:18 +01:00
package tools
import (
"strconv"
"strings"
"time"
)
// exported function(s)
func TimeToDDMMYYYY(time time.Time) string {
tmp := strconv.Itoa(time.Year())
for len(tmp) < 4 {
tmp = "0" + tmp
}
tmp = "." + tmp
tmp = strconv.Itoa(int(time.Month())) + tmp
for len(tmp) < 7 {
tmp = "0" + tmp
}
tmp = "." + tmp
tmp = strconv.Itoa(time.Day()) + tmp
for len(tmp) < 10 {
tmp = "0" + tmp
}
return tmp
}
func TimeToHHMMSS(time time.Time) string {
if time == ZeroDate {
return ""
}
2023-01-27 17:09:18 +01:00
tmp := strconv.Itoa(time.Second())
if len(tmp) < 2 {
tmp = "0" + tmp
}
tmp = ":" + tmp
tmp = strconv.Itoa(time.Minute()) + tmp
for len(tmp) < 5 {
tmp = "0" + tmp
}
tmp = ":" + tmp
tmp = strconv.Itoa(time.Hour()) + tmp
for len(tmp) < 8 {
tmp = "0" + tmp
}
return tmp
}
func DurationToHHMMSS(duration time.Duration) string {
2023-02-02 12:48:05 +01:00
negative := false
if duration < 0 {
duration = duration * -1
negative = true
}
2023-01-27 17:09:18 +01:00
durationSeconds := duration.Seconds()
durationHours := int(durationSeconds / 3600)
if durationHours > 0 {
durationSeconds = durationSeconds - float64(durationHours)*3600
}
durationMinutes := int(durationSeconds / 60)
if durationMinutes > 0 {
durationSeconds = durationSeconds - float64(durationMinutes)*60
}
tmpDuration := strconv.Itoa(int(durationSeconds))
for len(tmpDuration) < 2 {
tmpDuration = "0" + tmpDuration
}
tmpDuration = ":" + tmpDuration
tmpDuration = strconv.Itoa(int(durationMinutes)) + tmpDuration
for len(tmpDuration) < 5 {
tmpDuration = "0" + tmpDuration
}
tmpDuration = ":" + tmpDuration
tmpDuration = strconv.Itoa(int(durationHours)) + tmpDuration
for len(tmpDuration) < 8 {
tmpDuration = "0" + tmpDuration
}
2023-02-02 12:48:05 +01:00
if negative {
tmpDuration = "-" + tmpDuration
}
2023-01-27 17:09:18 +01:00
return tmpDuration
}
func DDMMYYToDate(date string) (time.Time, error) {
returnDate := time.Date(1, 1, 1, 0, 0, 0, 0, time.UTC)
if len(date) == 0 {
return returnDate, nil
}
parts := strings.Split(date, ".")
if len(parts) < 3 {
return returnDate, nil
}
days := 0
months := 0
years := 0
for index := 0; index < 3; index++ {
tmp, error := strconv.Atoi(parts[index])
if error != nil {
return returnDate, error
}
switch index {
case 0:
days = tmp
continue
case 1:
months = tmp
continue
case 2:
years = tmp
continue
}
}
returnDate = returnDate.AddDate(years-1, months-1, days-1)
return returnDate, nil
}