Custom data type for time representation (#86)
Co-authored-by: o.tyurin <o.tyurin@corp.mail.ru>
This commit is contained in:
31
core.go
31
core.go
@@ -5,6 +5,7 @@ import (
|
||||
"net/http"
|
||||
"reflect"
|
||||
"strconv"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
@@ -162,3 +163,33 @@ func TimeFromString(t *testing.T, format, datetime string) time.Time {
|
||||
}
|
||||
return dt
|
||||
}
|
||||
|
||||
const LayoutRequestDateDefault = "2006-01-02"
|
||||
|
||||
type RequestDate struct {
|
||||
time.Time
|
||||
layout string
|
||||
}
|
||||
|
||||
func NewRequestDate(t time.Time, layout string) *RequestDate {
|
||||
return &RequestDate{
|
||||
Time: t,
|
||||
layout: layout,
|
||||
}
|
||||
}
|
||||
|
||||
func (rd *RequestDate) UnmarshalJSON(b []byte) (err error) {
|
||||
s := strings.Trim(string(b), `"`) // remove quotes
|
||||
if s == "null" {
|
||||
return
|
||||
}
|
||||
rd.Time, err = time.Parse(rd.layout, s)
|
||||
return
|
||||
}
|
||||
|
||||
func (rd *RequestDate) MarshalJSON() ([]byte, error) {
|
||||
if rd.Time.IsZero() {
|
||||
return nil, nil
|
||||
}
|
||||
return []byte(fmt.Sprintf(`"%s"`, rd.Time.Format(rd.layout))), nil
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user