码迷,mamicode.com
首页 > 数据库 > 详细

golang time json mongodb 时间处理

时间:2019-12-15 10:34:56      阅读:170      评论:0      收藏:0      [点我收藏+]

标签:fun   nil   embed   lte   ODB   key   turn   make   onlayout   

golang 中解决前端time 输出,后端mongodb中时间存储。

package mask

import (
    "fmt"
    "time"

    "go.mongodb.org/mongo-driver/bson"
    "go.mongodb.org/mongo-driver/bson/bsontype"
)

// Timestamp extension time
type Timestamp struct {
    Time time.Time
}

const (
    jsonLayout = "2006-01-02 15:04:05"
)

// Now returns the current local time.
func Now() Timestamp {
    return Timestamp{
        Time: time.Now(),
    }
}

// UnmarshalBSON unmarshal bson
func (t *Timestamp) UnmarshalBSON(data []byte) (err error) {
    var d bson.D
    err = bson.Unmarshal(data, &d)
    if err != nil {
        return err
    }
    if v, ok := d.Map()["t"]; ok {
        t.Time = time.Time{}
        return t.Time.UnmarshalText([]byte(v.(string)))
    }
    return fmt.Errorf("key 't' missing")
}

// MarshalBSON marshal bson
func (t Timestamp) MarshalBSON() ([]byte, error) {
    txt, err := t.Time.MarshalText()
    if err != nil {
        return nil, err
    }
    b, err := bson.Marshal(map[string]string{"t": string(txt)})
    return b, err
}

// MarshalBSONValue marshal bson value
func (t *Timestamp) MarshalBSONValue() (bsontype.Type, []byte, error) {
    fmt.Println(t)
    b, err := bson.Marshal(t)
    return bson.TypeEmbeddedDocument, b, err
}

// UnmarshalJSON unmarshal json
func (t *Timestamp) UnmarshalJSON(data []byte) (err error) {
    if len(data) == 0 || string(data) == "" || string(data) == `""` {
        return
    }
    now, err := time.ParseInLocation(`"`+jsonLayout+`"`, string(data), time.Local)
    *t = Timestamp{
        Time: now,
    }
    return
}

// MarshalJSON marshal json
func (t Timestamp) MarshalJSON() ([]byte, error) {

    b := make([]byte, 0, len(jsonLayout)+2)
    b = append(b, '"')
    b = time.Time(t.Time).AppendFormat(b, jsonLayout)
    b = append(b, '"')
    return b, nil
}

golang time json mongodb 时间处理

标签:fun   nil   embed   lte   ODB   key   turn   make   onlayout   

原文地址:https://www.cnblogs.com/warrior/p/12042029.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!