简体   繁体   English

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

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

I have a model Open times for shops.我有一个 model 商店的营业时间。 The open times tables comprises a field as below.开放时间表包含如下字段。 I would like to query the opening and closing times like: 08:00 - 17:00我想查询开放和关闭时间,例如:08:00 - 17:00

t.time "closes"

the view helpers is the following: <%= display_day(0) %>.视图助手如下:<%= display_day(0) %>。 where 0 is sunday其中 0 是星期天

I get to the following array with pluck.我采摘到以下数组。

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

I would like to ignore the date component and only show Hours and Minutes.我想忽略日期部分,只显示小时和分钟。

Thanks to tadman and Caleb, we could get to the following:感谢 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

I will clean the code and post it there.我将清理代码并将其发布到那里。 in the meantime, if you have any suggestions, feel free to suggest.同时,如果您有任何建议,请随时提出建议。

You should be able to use both the DateTime parse and strftime methods to format the time however you want.您应该能够使用 DateTime parsestrftime方法来格式化您想要的时间。

Based on the plucking you're doing:根据你正在做的采摘:

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"

You could create a little formatting helper like:您可以创建一个小的格式化助手,例如:

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

And then use this to return the final string like: 08.00 - 17.00 :然后使用它返回最终的字符串,如: 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

Why don't you use the strftime method?为什么不使用 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