首页 > 解决方案 > Ruby:从 Ruby 生成 Google Protobuf 时间戳?

问题描述

这是一个模型blog

# id  :bigint(8)
#  created_at                  :datetime         not null
#  updated_at                  :datetime         not null

class Blog < ApplicationRecord

end

我想将模型的 created_at 和 updated_at 转换为 google Protobuf TimeStamp

blog = Blog.first
blog.created_at

形成protobuf消息时如何将DateTime转换为google Protobuf TimeStamp?

标签: ruby-on-railsrubyprotocol-buffers

解决方案


Google protobuf 库有方法可以做到这一点:

require 'google/protobuf/well_known_types'

# Convert ruby Time to protobuf value
time = Time.current
Google::Protobuf::Timestamp.new.from_time(time)

# Convert protobuf value to ruby Time
data = {:nanos=>801877000, :seconds=>1618811494}
Google::Protobuf::Timestamp.new(data).to_time

参见:https ://github.com/protocolbuffers/protobuf/blob/f763a2a86084371fd0da95f3eeb879c2ff26b06d/ruby/lib/google/protobuf/well_known_types.rb#L74-L97


推荐阅读