38 lines
775 B
Go
38 lines
775 B
Go
package server
|
|
|
|
import (
|
|
"encoding/json"
|
|
"fmt"
|
|
"strings"
|
|
"time"
|
|
)
|
|
|
|
type JSONDate time.Time
|
|
|
|
// UnmarshalJSON parses the JSONDate from a JSON input.
|
|
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
|
|
}
|
|
|
|
// MarshalJSON converts the JSONDate to a JSON in ISO format.
|
|
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
|
|
}
|
|
|
|
// Format formats the time using the regular time.Time mechanics..
|
|
func (j JSONDate) Format(s string) string {
|
|
t := time.Time(j)
|
|
return t.Format(s)
|
|
}
|