Date or Duration diff

This commit is contained in:
Mathieu Lecarme 2022-06-14 16:53:50 +02:00 committed by lperdereau
parent c11cbccb2d
commit 5edcdb6b57
2 changed files with 72 additions and 0 deletions

View file

@ -0,0 +1,25 @@
package loki
import (
"fmt"
"time"
)
type timestamp time.Time
func (t *timestamp) UnmarshalYAML(unmarshal func(interface{}) error) error {
var tt time.Time
err := unmarshal(&tt)
if err == nil {
*t = timestamp(tt)
return nil
}
var d time.Duration
err = unmarshal(&d)
if err == nil {
*t = timestamp(time.Now().Add(-d))
fmt.Println("t", time.Time(*t).Format(time.RFC3339))
return nil
}
return err
}

View file

@ -0,0 +1,47 @@
package loki
import (
"testing"
"time"
"gopkg.in/yaml.v2"
)
func TestTimestampFail(t *testing.T) {
var tt timestamp
err := yaml.Unmarshal([]byte("plop"), tt)
if err == nil {
t.Fail()
}
}
func TestTimestampTime(t *testing.T) {
var tt timestamp
const ts string = "2022-06-14T12:56:39+02:00"
err := yaml.Unmarshal([]byte(ts), &tt)
if err != nil {
t.Error(err)
t.Fail()
}
if ts != time.Time(tt).Format(time.RFC3339) {
t.Fail()
}
}
func TestTimestampDuration(t *testing.T) {
var tt timestamp
err := yaml.Unmarshal([]byte("3h"), &tt)
if err != nil {
t.Error(err)
t.Fail()
}
d, err := time.ParseDuration("3h")
if err != nil {
t.Error(err)
t.Fail()
}
z := time.Now().Add(-d)
if z.Round(time.Second) != time.Time(tt).Round(time.Second) {
t.Fail()
}
}