Back to Blog

Easy Datetime Comparison With ActiveRecord and Rails

Posted by Flatiron School on December 2, 2012

The following is a guest post by Stephen Chen and originally appeared on his blog. Stephen is a Flatiron School alumni. You can learn more about him here, or follow him on Twitter here.


TL;DR: Instead of creating or hardcoding your own DateTime and Date objects, use built in ActiveSupport methods in your ActiveRecord queries.

Using ActiveRecord is great because of all the built in functionality, but combine ActiveRecord with all the headaches that come with dates and datetime and it can get pretty intimidating. In most web applications that you build you’ll probably find yourself needing to filter a set of ActiveRecord objects by date, whether it is a date_created field or something else. These are a few things that made this extremely easy for me to understand. I’m not going to cover formatting datetime display because that is another post for another day.

Check the table

First of all, you want to inspect your database table schema and determine what type of field you are comparing against. Your ActiveRecord model can have either ‘date’ or ‘datetime’ data types so you’ll want to make sure you use the corresponding ‘Date’ or ‘DateTime’ Ruby classes. You can actually compare ‘Date’ and ‘DateTime’ objects against one another:

Blog post image: tumblr_me4f1efeWS1rtan47.png

However if you don’t realize that you are comparing two different types of data you may get unexpected results in your application.

Use built in ActiveSupport methods

“Active Support is a collection of various utility classes and standard library extensions that were found useful for Rails. All these additions have hence been collected in this bundle as way to gather all that sugar that makes Ruby sweeter.” – http://as.rubyonrails.org/

This is the documentation for the ActiveSupport DateTime methods: http://as.rubyonrails.org/classes/ActiveSupport/CoreExtensions/DateTime/Calculations.html

And this is the documentation for the ActiveSupport Date methods: http://as.rubyonrails.org/classes/ActiveSupport/CoreExtensions/Numeric/Time.html

With ActiveSupport you can easily query your database with ActiveRecord like this:

Blog post image: tumblr_me4f0lx9LE1rtan47.png

About Flatiron School

More articles by Flatiron School