开发者

Rails: seeding database data and date formats

开发者 https://www.devze.com 2023-02-20 18:01 出处:网络
I\'m trying to seed some data into a Rails 3 app that I\'m developing, using the db/seed.rb file and the rake db:seed command.

I'm trying to seed some data into a Rails 3 app that I'm developing, using the db/seed.rb file and the rake db:seed command.

The data I'm seeding involves a database table called Meeting that has three columns: string title, datetime startDate, datetime endDate. The datetimes I'm trying to insert are in "mm/dd/yyyy hh:mm" format -- eg. "01/02/2003 13:23" = January 2, 2003 1:23 PM. However, the DateTime.parse() is consistently erroring out with an "invalid date" error -- as it tr开发者_运维技巧ies to parse the dates in "dd/mm/yyyy" format.

From my Googling, I've been led to believe that when parsing DateTime objects the compiler looks at the string that's passed in and does some hasty pattern matching and then maps "mm/dd/yyyy" and "dd-mm-yyyy" accordingly per American/British(etc) standards based on whether a slash or a dash was used as a seperator. This doesn't seem to be the case, however, and I'm wondering why. And how to fix it.

This is how I'm seeding the Meetings -- the first one parses properly, the second one fails.

Meeting.create([
  {
    :title => "This meeting parses fine",
    :startDate => DateTime.parse("09/01/2009 17:00"),
    :endDate => DateTime.parse("09/01/2009 19:00")
  },
  {
    :title => "This meeting errors out",
    :startDate => DateTime.parse("09/14/2009 8:00")
    :endDate => DateTime.parse("09/14/2009 9:00")
  }])


You can try Date.strptime

:startDate => DateTime.parse("09/14/2009 8:00") 
#=> 
:startDate => DateTime.strptime("09/14/2009 8:00", "%m/%d/%Y %H:%M")

so

Meeting.create([
  {
    :title => "This meeting parses fine",
    :startDate => DateTime.strptime("09/01/2009 17:00", "%m/%d/%Y %H:%M"),
    :endDate => DateTime.strptime("09/01/2009 19:00", "%m/%d/%Y %H:%M")
  },
  {
    :title => "This meeting errors out",
    :startDate => DateTime.strptime("09/14/2009 8:00", "%m/%d/%Y %H:%M")
    :endDate => DateTime.strptime("09/14/2009 9:00", "%m/%d/%Y %H:%M")
  }])


Use DateTime.new instead. No worries about proper parsing then.

Meeting.create([
  {
    :title      => "This meeting parses fine",
    :startDate  => DateTime.new(2009,9,1,17),
    :endDate    => DateTime.new(2009,9,1,19)
  },
  {
    :title      => "This meeting errors out",
    :startDate  => DateTime.new(2009,9,14,8),
    :endDate    => DateTime.new(2009,9,14,9)
  }
])


If the specifics of the entered time aren't important, you can totally skip formatting with:

Time.now.to_datetime
Time.now.to_datetime.end_of_day


The easiest way to seed Date data that makes sense is using Gem Faker:

Gem https://github.com/faker-ruby/faker

Date https://github.com/faker-ruby/faker/blob/main/doc/default/date.md

0

精彩评论

暂无评论...
验证码 换一张
取 消