Skip to content

Instantly share code, notes, and snippets.

@smagch
Last active August 21, 2023 06:11
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save smagch/d2a55c60bbd76930c79f to your computer and use it in GitHub Desktop.
Save smagch/d2a55c60bbd76930c79f to your computer and use it in GitHub Desktop.
Golang: time without date
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