gob/datetime/parse.go

71 lines
1.4 KiB
Go

package datetime
import (
"strings"
"time"
. "gitea.zaclys.com/bvaudour/gob/option"
)
func isValueZero(e string) bool {
return e == "" || e == "0" || e == "0000-00-00 00:00:00" || e == "0000-00-00" || e == "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] {
case '\\': // Indique que le caractère suivant ne doit pas être parsé
buffer.WriteRune(runes[i+1])
i++
continue
default:
buffer.WriteRune(runes[i])
}
}
}
return buffer.String()
}
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)
}
return
}
func parseFromLayout(e, f string, tz ...string) (t Option[time.Time]) {
if isValueZero(e) {
return
}
return parseInLocation(e, f, tz...)
}
func guess(e string, tz ...string) (t Option[time.Time]) {
if isValueZero(e) {
return
}
switch e {
case "now":
return Some(now(tz...))
case "yesterday":
return Some(yesterday(tz...))
case "tomorrow":
return Some(tomorrow(tz...))
}
for _, l := range layouts {
if t = parseInLocation(e, l, tz...); t.IsDefined() {
break
}
}
return
}
func parse(e, f string, tz ...string) Option[time.Time] {
return parseFromLayout(e, format2layout(f), tz...)
}