Skip to content
Advertisement

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.

Advertisement

Answer

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
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement