简体   繁体   中英

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

I have a model Open times for shops. The open times tables comprises a field as below. I would like to query the opening and closing times like: 08:00 - 17:00

t.time "closes"

the view helpers is the following: <%= display_day(0) %>. where 0 is sunday

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:

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.

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 :

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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