【问题标题】:How to convert BSON::Timestamp to ruby time and vice versa如何将 BSON::Timestamp 转换为 ruby​​ 时间,反之亦然
【发布时间】:2021-09-07 02:09:02
【问题描述】:

我有一个红宝石哈希

input = {"dateCreated"=>#<BSON::Timestamp:0x00007fe0b482ca98 @increment=3745289216, @seconds=229>}

  1. 我们如何从 BSON 时间戳类中提取时间。

尝试输入["dateCreated"].as_json => {"$timestamp"=>{"t"=>244, "i"=>664779776}}

不知道如何继续。

  1. 如果有任何关于如何使用 ruby​​ 驱动程序根据时间戳值过滤到 MongoDB 的指针,我将不胜感激

.find()方法

【问题讨论】:

    标签: ruby mongodb timestamp bson


    【解决方案1】:

    您可以使用#to_bson 方法将BSON::Timestamp 转换为BSON::ByteBuffer

    然后,您可以将 BSON::ByteBuffer 转换为整数 (#get_int64),表示自纪元以来的毫秒数。

    然后使用Time::at 将该整数转换为Time 对象

    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
    

    【讨论】:

      【解决方案2】:

      您似乎拥有这种类型的对象:

      https://www.rubydoc.info/github/mongodb/bson-ruby/BSON/Timestamp

      来自gem

      还有这个object

      [6] pry(main)> bt = BSON::Timestamp.new(229, 3745289216)
      => #<BSON::Timestamp:0x00007fe338a79680 @increment=3745289216, @seconds=229>
      [7] pry(main)> # you allready have when begin the object in second 229
      [8] pry(main)> # you allready have when finish the even in secons in atribute increment 3745289216
      

      可能是这个值是 chage,因为时间从 1970 年开始,儿子用于翻译设置并使用方便的 gem 来操纵 rails 中使用的时间:

      [10] pry(main)> DateTime.strptime(bt.seconds.to_s,'%s')
      => #<DateTime: 1970-01-01T00:03:49+00:00 ((2440588j,229s,0n),+0s,2299161j)>
      
      [13] pry(main)> require 'active_support/core_ext/numeric/time.rb'
      => true
      
      [14] pry(main)> DateTime.strptime(bt.seconds.to_s,'%s') + bt.increment.seconds
      => Mon, 06 Sep 2088 06:10:45 +0000
      

      【讨论】:

      • 感谢您的解释。但是在 mongo 中,我创建了一个日期字段并给出了 2021-08-30T07:00:00.000+00:00 并将数据类型更改为时间戳。该值更改为 1630306800000。当我执行 Time.at(1630306800000/1000) 时,该值是正确的。但 mongo 结果为 BSON 格式 bt = #<:timestamp:0x00007fc504b12f30> [66] pry(main)> DateTime.strptime(bt.seconds.to_s,'%s') = > 1970 年 1 月 1 日星期四 00:06:19 +0000 [67] pry(main)> DateTime.strptime(bt.seconds.to_s,'%s') + bt.increment.seconds => 2049 年 9 月 2 日星期四 11 :33:15 +0000 最终值不匹配?
      猜你喜欢
      • 1970-01-01
      • 2021-08-31
      • 2014-04-17
      • 2016-09-20
      • 1970-01-01
      • 2011-01-23
      相关资源
      最近更新 更多