Here is a 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
blog = Blog.first
blog.created_at
How to convert DateTime to google Protobuf TimeStamp when forming a protobuf message?
Google protobuf library has methods to do it:
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
If you are using Ruby On Rails, you can do it in the following way:
## 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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With