这是一个模型blog。
# id :bigint(8)
# created_at :datetime not null
# updated_at :datetime not null
class Blog < ApplicationRecord
end我想将模型的created_at和updated_at转换为google
blog = Blog.first
blog.created_at如何在生成原型消息时将DateTime转换为google?
发布于 2021-04-20 08:21:36
库有方法可以做到这一点:
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请参阅:L74#L74-L97
发布于 2021-03-26 07:52:24
如果您正在使用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)参考文献
https://stackoverflow.com/questions/66541384
复制相似问题