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

Ruby: Generate Google Protobuf TimeStamp from Ruby?

这是一个模型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?

如果您在Rails上使用Ruby,您可以通过以下方式进行:

## 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

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