-
-
Save smagch/d2a55c60bbd76930c79f to your computer and use it in GitHub Desktop.
Golang: time without date
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"time" | |
"log" | |
"errors" | |
"encoding/json" | |
) | |
var timeLayout = "15:04" | |
var TimeParseError = errors.New(`TimeParseError: should be a string formatted as "15:04:05"`) | |
type Time struct { | |
time.Time | |
} | |
func (t Time) MarshalJSON() ([]byte, error) { | |
return []byte(`"` + t.Format(timeLayout) + `"`), nil | |
} | |
func (t *Time) UnmarshalJSON(b []byte) error { | |
s := string(b) | |
// len(`"23:59"`) == 7 | |
if len(s) != 7 { | |
return TimeParseError | |
} | |
ret, err := time.Parse(timeLayout, s[1:6]) | |
if err != nil { | |
return err | |
} | |
t.Time = ret | |
return nil | |
} | |
type Foo struct { | |
Id int `json:"id"` | |
Time Time `json:"time"` | |
} | |
type TimeRange [2]Time | |
type Bar struct { | |
FooId int `json:"foo_id"` | |
Ranges []TimeRange `json:"ranges"` | |
} | |
func fatalExit(err error) { | |
if err != nil { | |
log.Fatal(err) | |
} | |
} | |
func main() { | |
o := &Foo{1, Time{time.Now()}} | |
log.Println(o) | |
b, err := json.Marshal(o) | |
fatalExit(err) | |
log.Println(string(b)) | |
blob := []byte(`{"id":1,"time":"01:40"}`) | |
f := &Foo{} | |
err = json.Unmarshal(blob, f) | |
fatalExit(err) | |
str := f.Time.Format(timeLayout) | |
log.Printf("%+v, Time: %s\n", f, str) | |
b = []byte(` | |
{ | |
"foo_id": 1, | |
"ranges": [ | |
["10:00", "12:00"], | |
["13:00", "17:00"], | |
["17:45", "20:45"], | |
["22:00", "23:00"] | |
] | |
}`) | |
bar := &Bar{} | |
err = json.Unmarshal(b, bar) | |
fatalExit(err) | |
log.Println("%+v\n", bar) | |
b, err = json.Marshal(bar) | |
fatalExit(err) | |
log.Println(string(b)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment