【问题标题】:How do you store a string in MongoDB as a Date type using Ruby?如何使用 Ruby 将字符串作为日期类型存储在 MongoDB 中?
【发布时间】:2011-05-27 15:40:48
【问题描述】:

我从日志文件中解析出一个字符串,如下所示:

“[22/May/2011:23:02:21 +0000]”

什么是最好的方法(Ruby 中的示例将非常感谢,因为我正在使用 Mongo Ruby 驱动程序)将它作为原生 Date 类型隐藏到 MongoDB 中?

【问题讨论】:

    标签: ruby mongodb


    【解决方案1】:
    require 'date' # this is just to get the ABBR_MONTHNAMES list
    
    input = "[22/May/2011:23:02:21 +0000]"
    # this regex captures the numbers and month name
    pattern = %r{^\[(\d{2})/(\w+)/(\d{4}):(\d{2}):(\d{2}):(\d{2}) ([+-]\d{4})\]$}
    match = input.match(pattern)
    # MatchData can be splatted, which is very convenient
    _, date, month_name, year, hour, minute, second, tz_offset = *match
    # ABBR_MONTHNAMES contains "Jan", "Feb", etc.
    month = Date::ABBR_MONTHNAMES.index(month_name)
    # we need to insert a colon in the tz offset, because Time.new expects it
    tz = tz_offset[0,3] + ':' + tz_offset[3,5]
    # this is your time object, put it into Mongo and it will be saved as a Date
    Time.new(year.to_i, month, date.to_i, hour.to_i, minute.to_i, second.to_i, tz)
    

    需要注意的几点:

    • 我假设月份名称与ABBR_MONTHNAMES 列表中的相同,否则,只需创建您自己的列表。
    • 永远不要使用Date.parse 来解析日期,这非常慢,DateTime.parseTime.parse 也是如此,它们使用相同的实现。
    • 如果您解析许多不同的日期格式,请查看 home_run gem。
    • 如果您经常执行这些操作(就像您在解析日志文件时经常做的那样),请考虑不使用正则表达式。使用String#index#[]#split 提取您需要的部分。

    如果您想尽快完成此操作,则以下内容可能更合适。它不使用正则表达式(有用,但速度不快):

    date = input[1, 2].to_i
    month_name = input[4, 3]
    month = Date::ABBR_MONTHNAMES.index(month_name)
    year = input[8, 4].to_i
    hour = input[13, 2].to_i
    minute = input[16, 2].to_i
    second = input[19, 2].to_i
    tz_offset = input[22, 3].to_i * 60 * 60 + input[25, 2].to_i * 60
    Time.new(year, month, date, hour, minute, second, tz_offset)
    

    它利用了所有字段都具有固定宽度的事实(至少我认为它们是这样的)。所以你需要做的就是提取子字符串。它还将时区偏移量计算为数字而不是字符串。

    【讨论】:

      猜你喜欢
      • 2016-04-09
      • 2021-02-26
      • 1970-01-01
      • 1970-01-01
      • 2020-02-05
      • 1970-01-01
      • 2020-11-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多