gob/datetime/parse.go

71 lines
1.4 KiB
Go
Raw Normal View History

2023-10-31 10:18:00 +00:00
package datetime
import (
"strings"
"time"
. "gitea.zaclys.com/bvaudour/gob/option"
)
2023-11-03 19:33:26 +00:00
func isValueZero(e string) bool {
return e == "" || e == "0" || e == "0000-00-00 00:00:00" || e == "0000-00-00" || e == "00:00:00"
}
2023-10-31 10:18:00 +00:00
func format2layout(f string) string {
var buffer strings.Builder
runes := []rune(f)
for i := 0; i < len(runes); i++ {
if layout, ok := parsers[runes[i]]; ok {
buffer.WriteString(layout)
} else {
switch runes[i] {
2023-11-03 19:33:26 +00:00
case '\\': // Indique que le caractère suivant ne doit pas être parsé
2023-10-31 10:18:00 +00:00
buffer.WriteRune(runes[i+1])
i++
continue
default:
buffer.WriteRune(runes[i])
}
}
}
return buffer.String()
}
2023-11-03 19:33:26 +00:00
func parseInLocation(e, f string, tz ...string) (t Option[time.Time]) {
l := timezone(tz...)
if tt, err := time.ParseInLocation(f, e, l); err == nil {
t = Some(tt)
2023-10-31 10:18:00 +00:00
}
2023-11-03 19:33:26 +00:00
return
}
2023-10-31 10:18:00 +00:00
2023-11-03 19:33:26 +00:00
func parseFromLayout(e, f string, tz ...string) (t Option[time.Time]) {
if isValueZero(e) {
return
2023-10-31 10:18:00 +00:00
}
2023-11-03 19:33:26 +00:00
return parseInLocation(e, f, tz...)
2023-10-31 10:18:00 +00:00
}
2023-11-03 19:33:26 +00:00
func guess(e string, tz ...string) (t Option[time.Time]) {
if isValueZero(e) {
return
2023-10-31 10:18:00 +00:00
}
2023-11-03 19:33:26 +00:00
switch e {
2023-10-31 10:18:00 +00:00
case "now":
2023-11-03 19:33:26 +00:00
return Some(now(tz...))
2023-10-31 10:18:00 +00:00
case "yesterday":
2023-11-03 19:33:26 +00:00
return Some(yesterday(tz...))
2023-10-31 10:18:00 +00:00
case "tomorrow":
2023-11-03 19:33:26 +00:00
return Some(tomorrow(tz...))
2023-10-31 10:18:00 +00:00
}
2023-11-03 19:33:26 +00:00
for _, l := range layouts {
if t = parseInLocation(e, l, tz...); t.IsDefined() {
break
2023-10-31 10:18:00 +00:00
}
}
2023-11-03 19:33:26 +00:00
return
2023-10-31 10:18:00 +00:00
}
2023-11-03 19:33:26 +00:00
func parse(e, f string, tz ...string) Option[time.Time] {
return parseFromLayout(e, format2layout(f), tz...)
2023-10-31 10:18:00 +00:00
}