Skip to content

Instantly share code, notes, and snippets.

@surfacedamage
Created February 18, 2012 02:04
Show Gist options
  • Save surfacedamage/1856887 to your computer and use it in GitHub Desktop.
Save surfacedamage/1856887 to your computer and use it in GitHub Desktop.
Rails date parsing
# what is the best way to handle proper date parsing in rails given that
# i want to allow users to enter in mm/dd/yyyy format as single string
#schema.rb
ActiveRecord::Schema.define(:version => 20120218015632) do
create_table "people", :force => true do |t|
t.string "name"
t.date "birthdate"
t.datetime "created_at"
t.datetime "updated_at"
end
end
#app/models/person.rb
class Person < ActiveRecord::Base
end
# some consoling
irb: p = Person.create
SQL (0.8ms) INSERT INTO "people" ("birthdate", "created_at", "name", "updated_at") VALUES (?, ?, ?, ?) [["birthdate", nil], ["created_at", Sat, 18 Feb 2012 02:01:19 UTC +00:00], ["name", nil], ["updated_at", Sat, 18 Feb 2012 02:01:19 UTC +00:00]]
SQL (0.8ms) INSERT INTO "people" ("birthdate", "created_at", "name", "updated_at") VALUES (?, ?, ?, ?)
===> #<Person id: 3, name: nil, birthdate: nil, created_at: "2012-02-18 02:01:19", updated_at: "2012-02-18 02:01:19">
irb: p.birthdate = '04/29/1975'
===> "04/29/1975"
# note that the birthdate is nil
irb: p
===> #<Person id: 3, name: nil, birthdate: nil, created_at: "2012-02-18 02:01:19", updated_at: "2012-02-18 02:01:19">
irb: p.birthdate = '1975-04-29'
===> "1975-04-29"
# note that the birthdate is complete
irb: p.save
(1.4ms) UPDATE "people" SET "birthdate" = '1975-04-29', "updated_at" = '2012-02-18 02:01:47.049267' WHERE "people"."id" = 3
(1.4ms) UPDATE "people" SET "birthdate" = '1975-04-29', "updated_at" = '2012-02-18 02:01:47.049267' WHERE "people"."id" = 3
===> true
irb: p
===> #<Person id: 3, name: nil, birthdate: "1975-04-29", created_at: "2012-02-18 02:01:19", updated_at: "2012-02-18 02:01:47">
@surfacedamage
Copy link
Author

This is rails 3.1.3 with ruby 1.9.3.

A date of "04/29/1975" is invalid presumably because the parser doesn't know what to do with it.

Case in point:
Time.zone.parse("04/29/1975") #ArgumentError: invalid date
Time.zone.parse("1975-04-29") #Tue, 29 Apr 1975 00:00:00 UTC +00:00

So, my question is what is the best/proper way to handle allowing a user to enter a date in mm/dd/yyyy format (as a single field)? Some kind of before_validation filter?

@surfacedamage
Copy link
Author

@rubyist says to gem install american_date

I did.

And it worked.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment