Posted over 8 years ago. Visible to the public.

DateTimes are Dates, beware

Given:

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

will assert:

Copy
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:

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

And you say:

Copy
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:

Copy
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:

Copy
class Event < ActiveRecord::Base def day=(day) @day = day.to_date end end

Owner of this card:

Avatar
dncrht
Last edit:
over 6 years ago
by dncrht
Posted by dncrht to HouseTrip Deck
This website uses short-lived cookies to improve usability.
Accept or learn more