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

  1. package mask
  2. import (
  3. "fmt"
  4. "time"
  5. "go.mongodb.org/mongo-driver/bson"
  6. "go.mongodb.org/mongo-driver/bson/bsontype"
  7. )
  8. // Timestamp extension time
  9. type Timestamp struct {
  10. Time time.Time
  11. }
  12. const (
  13. jsonLayout = "2006-01-02 15:04:05"
  14. )
  15. // Now returns the current local time.
  16. func Now() Timestamp {
  17. return Timestamp{
  18. Time: time.Now(),
  19. }
  20. }
  21. // UnmarshalBSON unmarshal bson
  22. func (t *Timestamp) UnmarshalBSON(data []byte) (err error) {
  23. var d bson.D
  24. err = bson.Unmarshal(data, &d)
  25. if err != nil {
  26. return err
  27. }
  28. if v, ok := d.Map()["t"]; ok {
  29. t.Time = time.Time{}
  30. return t.Time.UnmarshalText([]byte(v.(string)))
  31. }
  32. return fmt.Errorf("key 't' missing")
  33. }
  34. // MarshalBSON marshal bson
  35. func (t Timestamp) MarshalBSON() ([]byte, error) {
  36. txt, err := t.Time.MarshalText()
  37. if err != nil {
  38. return nil, err
  39. }
  40. b, err := bson.Marshal(map[string]string{"t": string(txt)})
  41. return b, err
  42. }
  43. // MarshalBSONValue marshal bson value
  44. func (t *Timestamp) MarshalBSONValue() (bsontype.Type, []byte, error) {
  45. fmt.Println(t)
  46. b, err := bson.Marshal(t)
  47. return bson.TypeEmbeddedDocument, b, err
  48. }
  49. // UnmarshalJSON unmarshal json
  50. func (t *Timestamp) UnmarshalJSON(data []byte) (err error) {
  51. if len(data) == 0 || string(data) == "" || string(data) == `""` {
  52. return
  53. }
  54. now, err := time.ParseInLocation(`"`+jsonLayout+`"`, string(data), time.Local)
  55. *t = Timestamp{
  56. Time: now,
  57. }
  58. return
  59. }
  60. // MarshalJSON marshal json
  61. func (t Timestamp) MarshalJSON() ([]byte, error) {
  62. b := make([]byte, 0, len(jsonLayout)+2)
  63. b = append(b, '"')
  64. b = time.Time(t.Time).AppendFormat(b, jsonLayout)
  65. b = append(b, '"')
  66. return b, nil
  67. }

golang time json mongodb 时间处理

在mongodb go驱动程序中,如何将BSON封送/解封到结构中

Golang 和 MongoDB 中的 ISODate 时间交互问题

mongoDB对时间的处理ISODate与我们时区相差8小时