【问题标题】:Parsing Time field from Postgres db in rails 6 to retrieve hour and minute?从 Rails 6 中的 Postgres db 解析时间字段以检索小时和分钟?
【发布时间】:2019-10-31 20:46:03
【问题描述】:

我有一个模型商店的营业时间。开放时间表包含如下字段。我想查询开放和关闭时间如:08:00 - 17:00

t.time "closes"

视图助手如下:。其中 0 是星期天

我得到以下数组。

=> [Sat, 01 Jan 2000 08:00:00 UTC +00:00]

我想忽略日期部分,只显示小时和分钟。

感谢 tadman 和 Caleb,我们可以得到以下结果:

def display_day(value)
  is_open = @company.opentimes.where(day: value, openpublic: true)
  if is_open.pluck(:openpublic) == false
    'closed'
  else
    start = is_open.pluck(:opens)
    close = is_open.pluck(:closes)
    if start.nil?
      'no data'
    else
      DateTime.parse(start[0].to_s).strftime('%H.%M')
      DateTime.parse(close[0].to_s).strftime('%H.%M')
    end
  end
end

我将清理代码并将其发布到那里。同时,如果您有任何建议,请随时提出建议。

【问题讨论】:

  • 提示:在 Rails 中,您不想要 puts,而是希望返回该字符串。
  • 请注意,您可以在一个查询中获取这两个值:pluck(:opens, :closes)
  • 您可以随意格式化DateTime,通常使用带有格式说明符的to_s 或带有自定义格式字符串的strftime
  • 我不明白为什么你认为你首先要使用 pluck,因为它给你的是字符串而不是时间对象。只需遍历记录并使用strftime
  • 该代码也几乎完全被破坏了。 pluck 返回一个数组,所以@company.opentimes.where(day: value).pluck(:openpublic) == true 总是假的。

标签: sql ruby-on-rails ruby postgresql


【解决方案1】:

您应该能够同时使用 DateTime parsestrftime 方法来格式化您想要的时间。

根据你正在做的采摘:

start = @company.opentimes.where(day: value).pluck(:opens)
=> [Sat, 01 Jan 2000 08:00:00 UTC +00:00]

DateTime.parse(start[0].to_s).strftime('%H:%M')
=> "08:00"

您可以创建一个小的格式化助手,例如:

def format_time(time)
  DateTime.parse(time.to_s).strftime('%H.%M')
end

然后使用它返回最终的字符串,例如:08.00 - 17.00:

def hours_open(day)
  opentime = @company.opentimes.where(day: day, openpublic: true).first

  if opentime.opens && opentime.closes
    "#{format_time opentime.opens} - #{format_time opentime.closes}"
  elsif !opentime
    'closed'
  else
    'no data'
  end
end

【讨论】:

  • 谢谢。我可以使用 to_s 转换如下:'DateTime.parse(start[0].to_s).strftime('%H.%M')'
  • 我更新了我的答案并对您的最终解决方案进行了一些调整!让我知道这是否有用!
  • 一切都很好,但我已经用if opentime.try(:opens) && opentime.try(:closes)if opentime&.opens && opentime&.closes 进行了调整
【解决方案2】:

为什么不使用 strftime 方法?

Time.now.strftime('%T')    # this will output something like "15:26:54"
Time.now.strftime('%H:%M') # this will output something like "15:26"

【讨论】:

  • Marcelo,也许我错过了一些东西,但时间存储在 rails 的 pg 表中。所以我需要检索存储为时间的数据(时间字段不是日期时间)。当我这样做时:@model.@nested_model.c.opentimes.where(day:1, openpublic: true).pluck(:opens) 我检索该数据数组:[Sat, 01 Jan 2000 08:00:00 UTC +00:00]
  • 以下怎么办? @model.@nested_model.c.opentimes.where(day:1, openpublic: true).pluck(:opens).map { |d| d.strftime('%H:%M') }
猜你喜欢
  • 2018-09-28
  • 1970-01-01
  • 1970-01-01
  • 2020-08-15
  • 2017-11-12
  • 1970-01-01
  • 2021-04-02
  • 2013-07-03
  • 2018-03-06
相关资源
最近更新 更多