What is the difference between Date.today and Time.zone.today?

Daniel Pericich
2 min readJul 31, 2023

--

Photo by Ronan Furuta on Unsplash

We recently implemented the Rubocop linter for my team’s Ruby on Rails project. Our team has grown and changed over the last few years resulting in different design patterns, syntax, and overall implementation. Any senior developer will tell you that a uniform, consistent codebase is a good codebase, which is why linters can be so helpful. When refactoring some sections of our codebase I saw linting messages suggesting to use Time.zone.today instead of Date.today and wondered why it was better practice to do so.

What Ruby Objects Can Control Dates and Time?

Dynamically typed languages can be confusing as their lack of type systems allows developers to treat non-uniform types as if they were uniform. You can create objects for date and time using the Date, DateTime, and Time Ruby classes. While you can contort any of these objects to give you the value you want, you may not always get what you expect.

While it seems natural to use Date for getting objects related to months, years, and days and Time to handle time, both objects allow you to manipulate more. With Time you can modify the time through formatting and timezones, but also access date-related values off the Time object. This overlap of responsibilities makes picking the correct object for a task tricky.

What Decides My Timezone?

I thought that dates and times were the same no matter what Ruby object you used to instantiate them, but the Rubocop linter said otherwise. New versions of Ruby haven’t removed these types for redundancy because the types do have different behaviors. There is a reason to use the correct object type.

For displaying the correct timezone for a user, the Time object is the way to go. Time.zone uses the geo-information of a request (I.P. address or account) to set the time or defaults to the timezone defined in the Rails project’s application.rb file. This ensures a consistent or highly targeted time is returned on a user request.

The Date object is less predictable as it uses the app server’s timezone when deciding what value to use. This can lead to flaky behavior as users may not be in the same timezone as your servers, thus getting time and date values that do not reflect their current time. Even if you use multiple CDNs to get better user coverage, you still risk using the wrong dates.

This is why it is important to use Time.zone.today instead of Date.today to ensure proper behavior and date values for your users.

--

--

Daniel Pericich
Daniel Pericich

Written by Daniel Pericich

Former Big Beer Engineer turned Full Stack Software Engineer

No responses yet