github.com/CyCoreSystems/ari@v4.8.4+incompatible/datetime.go (about) 1 package ari 2 3 import ( 4 "encoding/json" 5 "strconv" 6 "time" 7 ) 8 9 // NOTE: near direct translation from ARI 2.0 10 11 // DateFormat is the date format that ARI returns in the JSON bodies 12 const DateFormat = "2006-01-02T15:04:05.000-0700" 13 14 // DateTime is an alias type for attaching a custom 15 // asterisk unmarshaller and marshaller for JSON 16 type DateTime time.Time 17 18 // MarshalJSON converts the given date object to ARIs date format 19 func (dt DateTime) MarshalJSON() ([]byte, error) { 20 t := time.Time(dt) 21 a := []byte("\"" + t.Format(DateFormat) + "\"") 22 return a, nil 23 } 24 25 // UnmarshalJSON parses the given date per ARIs date format 26 func (dt *DateTime) UnmarshalJSON(data []byte) error { 27 var stringDate string 28 err := json.Unmarshal(data, &stringDate) 29 if err != nil { 30 return err 31 } 32 33 t, err := time.Parse(DateFormat, stringDate) 34 if err != nil { 35 return err 36 } 37 *dt = (DateTime)(t) 38 return nil 39 } 40 41 func (dt DateTime) String() string { 42 t := (time.Time)(dt) 43 return t.String() 44 } 45 46 // Duration support functions 47 48 // DurationSec is a JSON type for duration in seconds 49 type DurationSec time.Duration 50 51 // MarshalJSON converts the duration into a JSON friendly format 52 func (ds DurationSec) MarshalJSON() ([]byte, error) { 53 return []byte(strconv.Itoa(int(time.Duration(ds) / time.Second))), nil 54 } 55 56 // UnmarshalJSON parses the data into the duration seconds object 57 func (ds *DurationSec) UnmarshalJSON(data []byte) error { 58 s, err := strconv.Atoi(string(data)) 59 if err != nil { 60 return err 61 } 62 63 *ds = DurationSec(time.Duration(s) * time.Second) 64 return nil 65 }