zoukankan      html  css  js  c++  java
  • golang time json mongodb 时间处理

    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
    }
    
    
  • 相关阅读:
    java容器01--初遇
    java虚拟机(1)--运行时数据区
    java虚拟机(2)--垃圾收集
    java虚拟机(3)--内存分配与回收策略
    java虚拟机(4)--类加载机制
    bash编程的信号捕获:
    awk纯干货
    shell中各种括号的作用()、(())、[]、[[]]、{}
    find
    awk
  • 原文地址:https://www.cnblogs.com/warrior/p/12042029.html
Copyright © 2011-2022 走看看