gpt4 book ai didi

go - Golang 中的时间戳

转载 作者:IT王子 更新时间:2023-10-29 01:02:42 25 4
gpt4 key购买 nike

尝试在我的应用程序中使用这种时间戳方法:https://gist.github.com/bsphere/8369aca6dde3e7b4392c#file-timestamp-go

这里是:

package timestamp

import (
"fmt"
"labix.org/v2/mgo/bson"
"strconv"
"time"
)

type Timestamp time.Time

func (t *Timestamp) MarshalJSON() ([]byte, error) {
ts := time.Time(*t).Unix()
stamp := fmt.Sprint(ts)

return []byte(stamp), nil
}

func (t *Timestamp) UnmarshalJSON(b []byte) error {
ts, err := strconv.Atoi(string(b))
if err != nil {
return err
}

*t = Timestamp(time.Unix(int64(ts), 0))

return nil
}

func (t Timestamp) GetBSON() (interface{}, error) {
if time.Time(*t).IsZero() {
return nil, nil
}

return time.Time(*t), nil
}

func (t *Timestamp) SetBSON(raw bson.Raw) error {
var tm time.Time

if err := raw.Unmarshal(&tm); err != nil {
return err
}

*t = Timestamp(tm)

return nil
}

func (t *Timestamp) String() string {
return time.Time(*t).String()
}

及其附带的文章:https://medium.com/coding-and-deploying-in-the-cloud/time-stamps-in-golang-abcaf581b72f

但是,我收到以下错误:

core/timestamp/timestamp.go:31: invalid indirect of t (type Timestamp)                                                                                                                                                     
core/timestamp/timestamp.go:35: invalid indirect of t (type Timestamp)

我的相关代码如下所示:

import (
"github.com/path/to/timestamp"
)

type User struct {
Name string
Created_at *timestamp.Timestamp `bson:"created_at,omitempty" json:"created_at,omitempty"`
}

谁能看出我做错了什么?

相关问题我也看不到如何实现这个包。我要创建一个像这样的新用户模型吗?

u := User{Name: "Joe Bloggs", Created_at: timestamp.Timestamp(time.Now())}

最佳答案

您的代码有错字。你不能取消引用一个非指针,所以你需要让 GetBSON 成为一个指针接收器(或者你可以删除对 t 的间接访问,因为 t 的值是' t 由方法改变)。

func (t *Timestamp) GetBSON() (interface{}, error) {

要内联设置一个*Timestamp值,你需要有一个*time.Time来转换。

now := time.Now()
u := User{
Name: "Bob",
CreatedAt: (*Timestamp)(&now),
}

构造函数和辅助函数,如 New()Now() 也可以派上用场。

关于go - Golang 中的时间戳,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32015364/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com