sql >> Base de Datos >  >> NoSQL >> MongoDB

Cómo convertir BSON::Timestamp a ruby ​​time y viceversa

Puede convertir un BSON::Timestamp a un BSON::ByteBuffer usando el #to_bson método.

A continuación, puede convertir el BSON::ByteBuffer a un número entero (#get_int64 ) que representa el número de milisegundos desde la época.

Luego use Time::at para convertir ese entero a un Time objeto

date_time = DateTime.new(2021,8,30)
date_time.to_time
#=> 2021-08-30 00:00:00 +0000
date_time.to_time.to_i
#=> 1630281600 
timestamp = BSON::Timestamp.from_bson(date_time.to_bson)
#=> #<BSON::Timestamp:0x00007fffe31da4a8 @seconds=379, @increment=2488994816>
timestamp.to_bson.get_int64 / 1000 
#=> 1630281600
Time.at(timestamp.to_bson.get_int64 / 1000).utc
#=> 2021-08-30 00:00:00 UTC