从RethinkDB获取时间

huangapple go评论104阅读模式
英文:

go - Get time from RethinkDB

问题

我在Go中有一个名为Quote的结构体:

type Quote struct {
	CreatedAt int64 `gorethink:"createdAt"`
	// 其他字段...
}

我编写了一个查询RethinkDB数据的代码,并成功执行了:

result, err := r.Table("quote").GetAll(ids...).Run(session)
defer result.Close()

if err != nil {
	fmt.Println(err)
}

var quotes []Quote
err = result.All(&quotes)

它确实返回了正确的结果,但是CreatedAt字段中的记录没有值。我在数据库中使用的createdAt的时间格式是以毫秒为单位的UTC纪元时间,我打算将它们作为数字在之后进行计算。

我在Go文档中找到了以下内容:

func (t Time) Unix() int64

所以我认为int64应该是CreatedAt字段的正确类型,但是它不起作用。我该怎么办?如何获取时间数据?

time.Time也不起作用。如果使用time.Time,结果始终为0001-01-01 00:00:00 +0000 UTC(如果转换为毫秒,则为0值)。

因为当我在Node.js中构建相同的服务器时,我使用了Date.Now(),所以我需要在这种情况下寻找一个等效的类型,它返回一个数字,以便我之后进行计算。

英文:

I have a struct Quote in Go

type Quote struct{
	CreatedAt int64 `gorethink:"createdAt"`
    // Other fields...
}

I write to query data from RethinkDB and succeed

result,err:=r.Table("quote").GetAll(ids...).Run(session)

defer result.Close()
		
		if err!=nil{
			fmt.Println(err)
		}
		var quotes []Quote
		err=result.All(&quotes)

It does get true results, but none of records has value in CreatedAt field. The time format I use for createdAt in database is milliseconds since epoch UTC, I intend to use them as number to calculate after

I read GoDocs for time and found:

func (t Time) Unix() int64

So I thought int64 would be the right type for CreatedAt, but it didn't work. What should I do? How can I get time data?

time.Time doesn't work as well. If time.Time is used, the result is always 0001-01-01 00:00:00 +0000 UTC (similarly 0 value if converted to milliseconds)

Because when I built the same server in NodeJS I used Date.Now(), I need to seek an equivalent type in this case, which returns a number for me to calculate later process

答案1

得分: 3

当使用gorethink时,驱动程序将自动转换为GO的本机数据类型。将您的结构更改为使用time.Time

type Quote struct{
    CreatedAt   time.Time  `gorethink:"created_at"`
}

您可以查看相应的测试用例以获取更多示例。

英文:

When using gorethink the driver will automatically convert to and from GO’s native data types. Change your struct to use time.Time:

type Quote struct{
    CreatedAt   time.Time  `gorethink:"created_at"`
}

For more samples you can check the respective test cases.

答案2

得分: 0

我成功找到了答案。在这种情况下,使用的是float64类型,以便获取的结果与数据库浏览器中的匹配(例如,1458184908597毫秒)。

英文:

I managed to find the answer myself. True type is used in this condition is float64 so that results fetched match with in database explorer (for example, 1458184908597 milliseconds)

huangapple
  • 本文由 发表于 2016年3月22日 17:01:28
  • 转载请务必保留本文链接:https://go.coder-hub.com/36150021.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定