carpool-service/interoperability/ocss/time.go

63 lines
1.1 KiB
Go

package ocss
import (
"encoding/json"
"fmt"
"time"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/bson/bsontype"
"go.mongodb.org/mongo-driver/x/bsonx/bsoncore"
)
type OCSSTime time.Time
func (t OCSSTime) MarshalJSON() ([]byte, error) {
//do your serializing here
stamp := fmt.Sprintf("%v", time.Time(t).Unix())
return []byte(stamp), nil
}
func (v OCSSTime) MarshalBSONValue() (bsontype.Type, []byte, error) {
return bson.MarshalValue(time.Time(v))
}
func (t *OCSSTime) UnmarshalJSON(b []byte) error {
var timestamp int64
err := json.Unmarshal(b, &timestamp)
if err != nil {
return err
}
parsed := time.Unix(timestamp, 0)
if err != nil {
return err
}
ocsstime := OCSSTime(parsed)
*t = ocsstime
return nil
}
func (t *OCSSTime) UnmarshalBSONValue(bt bsontype.Type, b []byte) error {
if bt == bsontype.Null || len(b) == 0 {
return nil
}
datetime, _, ok := bsoncore.ReadTime(b)
if !ok {
return fmt.Errorf("cannot parse time")
}
*t = OCSSTime(datetime)
return nil
}
func (t *OCSSTime) ToTime() *time.Time {
if t == nil {
return nil
}
time := time.Time(*t)
return &time
}