budgeteer/http/json-date.go
2022-02-15 12:37:04 +00:00

37 lines
687 B
Go

package http
import (
"encoding/json"
"fmt"
"strings"
"time"
)
type JSONDate time.Time
// Implement Marshaler and Unmarshaler interface
func (j *JSONDate) UnmarshalJSON(b []byte) error {
s := strings.Trim(string(b), "\"")
t, err := time.Parse("2006-01-02", s)
if err != nil {
return fmt.Errorf("parse date: %w", err)
}
*j = JSONDate(t)
return nil
}
func (j JSONDate) MarshalJSON() ([]byte, error) {
result, err := json.Marshal(time.Time(j))
if err != nil {
return nil, fmt.Errorf("marshal date: %w", err)
}
return result, nil
}
// Maybe a Format function for printing your date
func (j JSONDate) Format(s string) string {
t := time.Time(j)
return t.Format(s)
}