Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails 12 hour AM/PM range for a day

This is a really simple question, and it's probably been asked and answered before, but I haven't been able to find anything.

Anyway, I need a range/array for 12 hour time, so like 12AM - 11AM, 12PM - 11PM. You probably get the gist of it. Right now I'm trying to do an absurdly complicated method involving mapping AM onto one array, PM onto another one, and then joining the two arrays together. There has to be an easier way to do this.

I know about Rails time_select, but I need a different format than what it provides. Any suggestions?

Clarification: So what I'm looking for is the 12-hour clock, with AM and PM. If I wanted a 24-hour clock, I could just do (0..24), and be done. But the 12-hour clock goes from 12-11 AM, and then goes from 12-11 PM. I'm pretty sure someone has done this before.

like image 774
irosenb Avatar asked Aug 01 '13 17:08

irosenb


2 Answers

I agree with @MrYoshi's comment, the easiest way of formatting a date is .strftime(), see RubyDoc for all possible options

Example:

Time.now.strftime("%I:%M %p")

output: HH:MM AM

Or what you literally asked for:

Time.now.strftime("%I:00")

output: HH:00

As you mentioned time_select I assume you want to offer time as a user selectable range, so try these options for time_select(more options):

time_select 'game', 'game_time', {:minute_step => 60, :ampm => true}

also this previous question: Time select form helper with 12 hour format for Rails 3?

like image 93
caffeinated.tech Avatar answered Sep 19 '22 04:09

caffeinated.tech


Rails does this built in

   <%= f.time_select :start,  {ampm: true} %>  

http://api.rubyonrails.org/classes/ActionView/Helpers/DateHelper.html#method-i-time_select

like image 37
Will Avatar answered Sep 20 '22 04:09

Will