0

I have the following code in my seeds.rb file:

# create a 7 day wall
for day in 1..7
    # create the days
    d = Day.create(day: day)
    # for each day create the time slots. Use 15 minute timeslots for now
    start_time = Time.new.beginning_of_day
    puts start_time
    end_time = start_time.end_of_day
    puts end_time
    begin
            d.time_slots << TimeSlot.create(time: start_time)
            start_time += 15.minutes
            puts start_time
    end while start_time <= end_time
            puts "Start time after exit: #{start_time}"

    campaign.days << d
end

It creates right output as one would expect

2013-04-19 00:00:00 -0700
2013-04-19 23:59:59 -0700
2013-04-19 00:15:00 -0700
2013-04-19 00:30:00 -0700
2013-04-19 00:45:00 -0700
2013-04-19 01:00:00 -0700
2013-04-19 01:15:00 -0700
2013-04-19 01:30:00 -0700
2013-04-19 01:45:00 -0700
2013-04-19 02:00:00 -0700
2013-04-19 02:15:00 -0700
2013-04-19 02:30:00 -0700
2013-04-19 02:45:00 -0700
2013-04-19 03:00:00 -0700
2013-04-19 03:15:00 -0700
2013-04-19 03:30:00 -0700
....

When I look in the my db using sqlite browser, I see this too. When use my rails console to inspect the database I see:

1.9.3p194 :001 > TimeSlot.find(1)
  TimeSlot Load (17.3ms)  SELECT "time_slots".* FROM "time_slots" WHERE "time_slots"."id" = ? LIMIT 1  [["id", 1]]
 => #<TimeSlot id: 1, time: "2000-01-01 07:00:00", created_at: "2013-04-19 21:56:58", updated_at: "2013-04-19 21:56:58", campaign_id: nil, day_id: 1>

Why is the record in the database showing the wrong date? The timestamps are right, but the time field is wrong. I don't get it.

Jeffrey Guenther
  • 871
  • 10
  • 27
  • 1
    are you storing it as a `time` column or a `datetime` column in your database? if it's the first case i believe this could help you: http://stackoverflow.com/questions/2760963/time-fields-in-rails-coming-back-blank – Zippie Apr 19 '13 at 22:56
  • Yes, I am using `time`. – Jeffrey Guenther Apr 19 '13 at 23:05

1 Answers1

0

There are two things going on in this problem:

  1. There is some nuance to using time and datetime types in rails. See Time fields in Rails coming back blank
  2. The time zone is an issue. The db stores times in UTC/GMT. When Time.new is called it uses the system's current timezone.

The code to increment the time object is right. I just need to take the timezone into account when I'm displaying the times.

Community
  • 1
  • 1
Jeffrey Guenther
  • 871
  • 10
  • 27