我正在尝试在我的应用程序中使用这种时间戳方法: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())}
created_at
字段的新用户。 - tommyd456*Timestamp
的示例。 - JimB