Basic date_select questions


#1

Hello,

I’ve done a bunch of searches but I can’t seem to find answers to
these simple questions.

  1. When I use date_select, it uses Ruby’s Time.now, which is based on
    server time, which is on GMT. I want date_select to use client-side
    time since this is an app that will potentially be used around the
    world.

  2. I want a “today” or “yesterday” text link to the side of the 3
    dropdowns that would change the value of the dropdowns to today or
    yesterday’s date. I know how I’d do this with javascript, but I
    wonder if there’s a good way to do this in Rails.

Thanks!


#2

There are a few different approaches for #1. First off if you want to
do time zone conversions of dates you should grab the TZInfo Ruby lib
from http://tzinfo.rubyforge.org/ which will handle the tricky
business of daylight saving time. To process time zones on the server
you will need to ask the user for their preferred time zone by
building a select list from TZInfo (there are instructions for doing
this in the TZInfo documentation) and then storing the selection for
later processing – preferably in some kind of user account so the
user doesn’t have to re-select time zone every time they visit your
app. After you have stored the user’s time zone you can easily use
TZInfo to convert dates in to and out of local times. Another option
is to do all date conversions on the client which I think would
require spitting out some javascript from the server with timezone
info (probably from TZInfo) and then converting times to UTC before
post back. Peter M. has a blog post about this topic at http://
www.marklunds.com/articles/one/311 which may be helpful and there is a
comment on that page from someone doing conversions on the client.

#2 can be done pretty easily with a button_to or link_to for an action
that set’s the default. First set the default value of the select to
some variable you define in the controller:

View:
<%= select_datetime @mydatetime %>

Controller:
def index
@mydatetime = Time.now
end

Then have a button or link that calls an action on the controller to
set that value:

View:
<%= button_to “yesterday”, :action => “yesterday” %>

Controller:
def yesterday
@mydatetime = Time.now.yesterday
render :action => :index
end

When the “yesterday” button is clicked the form will re-render with
yesterday’s date. Of course the much slicker way of doing this would
be to use form_remote_tag and link_to_remote to make an AJAX call to a
yesterday action but that’s a bit trickier and probably out of scope
for the question.