Get a hash/array with a range of dates?

I’m trying to build options for a select box that would output a range
of dates between two dates that I specified. For example, if my two
dates (both coming from datetime fields in a MySQL database) were:

October 25th, 2006
October 29th, 2006

I’d like to output options like this:

(option value=“2006-10-25”)October 25th, 2006(/option)
(option value=“2006-10-26”)October 26th, 2006(/option)
(option value=“2006-10-27”)October 27th, 2006(/option)
(option value=“2006-10-28”)October 28th, 2006(/option)
(option value=“2006-10-29”)October 29th, 2006(/option)

I can’t figure out how to get the range of dates into a collection. I
tried doing:
@range_of_dates = @first_date@second_date

But it didn’t work. Does anyone know how I can do this?

Thanks,
Sean

Ruby DATE class implements the “upto” method, so assuming you can
massage @first_date and @second_date as DATE objects, you should be able
to do something like this (in your view):

<% @first_date.upto(@second_date) do |date| %>
(option value="<% date.to_s %>")<% date.to_s %>(/option)
<% end %>

Of course, you’ll need to massage the output of date.to_s to get the
formats that you want - strftime method does this for Time objects, not
sure if it applies for Date objects.

c.

Sean wrote:

I’m trying to build options for a select box that would output a range
of dates between two dates that I specified. For example, if my two
dates (both coming from datetime fields in a MySQL database) were:

October 25th, 2006
October 29th, 2006

I’d like to output options like this:

(option value=“2006-10-25”)October 25th, 2006(/option)
(option value=“2006-10-26”)October 26th, 2006(/option)
(option value=“2006-10-27”)October 27th, 2006(/option)
(option value=“2006-10-28”)October 28th, 2006(/option)
(option value=“2006-10-29”)October 29th, 2006(/option)

I can’t figure out how to get the range of dates into a collection. I
tried doing:
@range_of_dates = @first_date@second_date

But it didn’t work. Does anyone know how I can do this?

Thanks,
Sean

Another option…

In your controller:

@range_of_dates = @first_date.upto(@second_date).map {|date| [date.to_s,
date.to_s]}

In your view:

<%= select(‘object’,‘method’,@range_of_dates) %>

Again, you’ll want to get the formats of the date.to_s correct in the
first line of code. The first date.to_s is what is used for the display,
the second is what is used for the value.

c.

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs