簡體   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