DateTimes are Dates, beware

Posted About 11 years ago. Visible to the public.

Given:

datetime = DateTime.now
date = datetime.to_date #or Date.today

will assert:

datetime.is_a? Date == true
datetime.is_a? DateTime == true
datetime.instance_of? Date == false
datetime.instance_of? DateTime == true

In case you have a table and a model like:

create_table :event do |t|
  t.date    :day
  t.string  :description
end
class Event < ActiveRecord::Base; end

And you say:

event = Event.new(:day => '2013-03-22')

Rails will convert the supplied value for day to the type of the database field, a Date.

BUT, if you say:

event = Event.new(:day => datetime)

Rails will not convert anything, and it will remain as a DateTime until it's persisted. Then the database will truncate the time information and will be saved as a date indeed.

Consider this if you have methods on your model that deal with dates, because if you provide a DateTime you could get unexpected results. You might force the type of the fields to Date upon assignment:

class Event < ActiveRecord::Base
  def day=(day)
    @day = day.to_date
  end
end
dncrht
Last edit
Almost 9 years ago
dncrht
Posted by dncrht to HouseTrip Deck (2013-03-22 10:41)