Ruby:如何从Ruby生成Google Protobuf时间戳?

3
这是一个模型博客。
# id  :bigint(8)
#  created_at                  :datetime         not null
#  updated_at                  :datetime         not null

class Blog < ApplicationRecord

end

我想将模型的created_at和updated_at转换为Google Protobuf时间戳。
blog = Blog.first
blog.created_at

如何在组成protobuf消息时将DateTime转换为Google Protobuf TimeStamp?
如何在组成protobuf消息时将DateTime转换为Google Protobuf TimeStamp?

你已经看过 https://dev59.com/XJ7ha4cB1Zd3GeqPgkE1 了吗? - undefined
2个回答

5

1
如果你正在使用Ruby On Rails,你可以按照以下方式进行:
## Convert Ruby DateTime to Google::Protobuf::Timestamp
time = DateTime.now
seconds = time.to_i
nanos = time.nsec
gpt = Google::Protobuf::Timestamp.new(seconds: seconds, nanos: nanos)


## Convert Google::Protobuf::Timestamp to ruby DateTime
micros = gpt.nanos / 10 ** 3
time2 = Time.at(gpt.seconds, micros)

参考资料

  1. ActiveSupport: DateTime#nsec
  2. Stack Overflow: 如何将 google.protobuf.Timestamp 转换为 Ruby 的 DateTime 对象?

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接