繁体   English   中英

从 Rails 6 中的 Postgres db 解析时间字段以检索小时和分钟?

[英]Parsing Time field from Postgres db in rails 6 to retrieve hour and minute?

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

t.time "closes"

视图助手如下:<%= display_day(0) %>。 其中 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

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

您应该能够使用 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

为什么不使用 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"

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM