views:

41

answers:

1

I created a form with scaffold that includes two datetime fields. I replaced them with a datepicker, and now I'm trying to grab the date from within the controller. Instead of having ruby do all the magic work with the datefields, I instead just have to fields, start_date and stop_date that I want to use, but I can't figure out how to grab them from within my controller. Hints? Thanks!

A: 

You have at least two options:

  • Try using Time.parse(params[:start_date]) (which does a REALLY good job)
  • Try to parse out the contents yourself. (which I won't even recommend)

I've been using Time.parse with a full success rate. BUT keep in mind that if your app crosses country boundaries, the parse for months and days might get reversed. (i.e. 10/1/2008 in Brazil is really January 10, 2008, compared to the US standard October 1, 2008).

EDIT:

Here's an example with a test application that runs on SQLite. It should work the same way for you. Let me know if it doesn't:

>> a = Post.first
=> #<Post id: 1, title: "title 1 ", updated_by: nil, deleted_by: 1, created_at: "2009-11-23 18:48:23", updated_at: "2009-11-23 18:48:23">
>> a.updated_at = Time.parse('01/02/2010')
=> Sat Jan 02 00:00:00 -0500 2010
>> a.save
  Post Update (44.9ms)   UPDATE "posts" SET "updated_at" = '2010-02-03 12:59:32' WHERE "id" = 1
=> true
>> 
btelles
Thanks! You led me to the answer, but I think my solution is sloppy. My date starts out as a string '01/02/2010'. When I call Time.parse on it it says 'argument out of range'. At one point I had it working but it looked like '2010-01-02 00:00:00 -0000', however my sqlite datetime field won't accept that. It wants it to look like '2010-01-02 00:00:00'. What's the trick?
99miles
I've added to my answer...I'm pretty sure Time.parse should work with SQLite.
btelles
Yes, that is getting put into the database. Not sure what I was doing wrong before. Unfortunately it is mixing up the month and day. My string is in the format month/day/year. So Time.parse(02/03/2010) (Feb 3, 2010) is getting put into the database with the day and month reversed (2010-05-02 instead of 2010-02-05), which is surprising, and I believe the reverse of what you were saying. Looks like I have to stick with my little parser method.
99miles
all right...sorry I couldn't be more help.
btelles