Easy Datetime Comparison With ActiveRecord and Rails

You’re closer than you think to a career in tech. Our grads have launched rewarding new careers — you can too.

View Our Jobs Report

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

Headshot of Flatiron School

Flatiron School

Blog Post Author

Read More Flatiron School Articles

Since we opened our doors in 2012, thousands of students have joined Flatiron School to launch new careers in tech.

Explore our Courses

Find the perfect course for you across our in-person and online programs designed to power your career change.

Explore Our Courses
Join a Community

Connect with students and staff at meetups, lectures, and demos – on campus and online.

Join the Community
Schedule a Chat

Have a question about our programs? Our admissions team is here to help.

Schedule a Chat