简体   繁体   English

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

[英]Ruby: Generate Google Protobuf TimeStamp from Ruby?

Here is a model blog .这是 model blog

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

class Blog < ApplicationRecord

end

I would like to convert model's created_at and updated_at to google Protobuf TimeStamp我想将模型的 created_at 和 updated_at 转换为 google Protobuf TimeStamp

blog = Blog.first
blog.created_at

How to convert DateTime to google Protobuf TimeStamp when forming a protobuf message?形成protobuf消息时如何将DateTime转换为google Protobuf TimeStamp?

If you are using Ruby On Rails, you can do it in the following way:如果您使用的是 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)

Reference参考

  1. ActiveSupport: DateTime#nsec ActiveSupport: 日期时间#nsec
  2. Stack Overflow: How can we convert google.protobuf.Timestamp to Ruby DateTime object? 堆栈溢出:我们如何将 google.protobuf.Timestamp 转换为 Ruby DateTime object?

Google protobuf library has methods to do it: 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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM