stillbox/internal/jsontypes/jsontime.go

139 lines
2.3 KiB
Go
Raw Normal View History

2024-11-13 09:24:11 -05:00
package jsontypes
2024-10-30 09:49:45 -04:00
import (
"encoding/json"
"strings"
"time"
"github.com/araddon/dateparse"
"github.com/jackc/pgx/v5/pgtype"
2024-10-30 09:49:45 -04:00
"gopkg.in/yaml.v3"
)
type Time time.Time
func (t *Time) UnmarshalYAML(n *yaml.Node) error {
var s string
err := n.Decode(&s)
if err != nil {
return err
}
tm, err := dateparse.ParseAny(s)
if err != nil {
return err
}
*t = Time(tm)
return nil
}
2024-12-29 09:30:24 -05:00
func TimePtrFromTSTZ(t pgtype.Timestamptz) *Time {
if t.Valid {
return (*Time)(&t.Time)
}
return nil
}
func (t *Time) PGTypeTSTZ() pgtype.Timestamptz {
if t == nil {
return pgtype.Timestamptz{Valid: false}
}
return pgtype.Timestamptz{
Time: time.Time(*t),
Valid: true,
}
}
2024-10-30 09:49:45 -04:00
func (t *Time) UnmarshalJSON(b []byte) error {
s := strings.Trim(string(b), `"`)
tm, err := dateparse.ParseAny(s)
if err != nil {
return err
}
*t = Time(tm)
return nil
}
func (t Time) MarshalJSON() ([]byte, error) {
return json.Marshal(time.Time(t))
}
func (t Time) String() string {
return time.Time(t).String()
}
func (t Time) Time() time.Time {
return time.Time(t)
}
type Duration time.Duration
func (d *Duration) UnmarshalYAML(n *yaml.Node) error {
var s string
err := n.Decode(&s)
if err != nil {
return err
}
dur, err := time.ParseDuration(s)
if err != nil {
return err
}
*d = Duration(dur)
return nil
}
2024-11-24 09:10:31 -05:00
func (d *Duration) UnmarshalText(text []byte) error {
dur, err := time.ParseDuration(string(text))
if err != nil {
return err
}
*d = Duration(dur)
return nil
}
2024-10-30 09:49:45 -04:00
func (d *Duration) UnmarshalJSON(b []byte) error {
s := strings.Trim(string(b), `"`)
dur, err := time.ParseDuration(s)
if err != nil {
return err
}
*d = Duration(dur)
return nil
}
func (d Duration) MarshalJSON() ([]byte, error) {
return json.Marshal(time.Duration(d))
}
func (d Duration) Duration() time.Duration {
return time.Duration(d)
}
func (d Duration) String() string {
return time.Duration(d).String()
}
func ParseDuration(s string) (Duration, error) {
d, err := time.ParseDuration(s)
return Duration(d), err
}
func ParseAny(s string, opt ...dateparse.ParserOption) (Time, error) {
t, err := dateparse.ParseAny(s, opt...)
return Time(t), err
}
2024-10-31 09:09:58 -04:00
func ParseLocal(s string, opt ...dateparse.ParserOption) (Time, error) {
t, err := dateparse.ParseLocal(s, opt...)
2024-10-30 09:49:45 -04:00
return Time(t), err
}