Since 1999

 

3 minutes estimated reading time.

Get the Current Year in the Ruby programming language

When learning Ruby on Rails, sometimes you just need to get the current year as a number. I posted one example on why this is a useful way on a real-life website in the 2011 post on how to automatically update copyright notices.

In this article, I will show you some methods for getting the current year, such as the number 2015. I will then show you how to benchmark the methods to determine which is the fastest method for you, given your machine and Ruby version.

Okay, just how do I get the Current Year in Ruby?

It’s easy. Just use any of the Date/Time objects and call the year method, like this:

   # Using the Time class
   current_year = Time.new.year  # or Time.now.year

   # Using the Date class
   current_year = Date.today.year

   # Using the DateTime class
   current_year = DateTime.now.year


If you want to just throw this information in a view, then something like this in your ERB should be good.

  <p>
    The current year is <span id="year"><%= Date.today.year %></span>.
  </p>

And, if you want the numerical month of the year

current_month = Date.today.month

Benchmarking the performance of the options

If you are into profiling code, check out Joshua McGees' 2013 post on the same topic, Getting the current year in Ruby on Rails (eclecticquill.com). According to his findings with Ruby at the time, Time.new.year was significantly faster than Date.current.year (which is available in Ruby on Rails, but is not in the standard Ruby library).

My benchmarks

I have decided to try out the same benchmark test on my 2014 MacBook Pro, a 2.8 GHz Intel Core i7.

The benchmark code that I ran in IRB

  # Let's measure the performance of some methods for getting the current year
  require 'benchmark'
  require 'date'
  n = (10**6)
  puts Benchmark.realtime { n.times { Date.today.year } }
  puts Benchmark.realtime { n.times { DateTime.now.year } }
  puts Benchmark.realtime { n.times { Time.now.year } }
  puts Benchmark.realtime { n.times { Time.new.year } }
  # Done

Timing results

Method Ruby 2.2 JRuby 1.7.19
Date.today.year 1.176 1.697
DateTime.now.year 1.110 3.132
Time.now.year 1.282 0.314
Time.new.year 1.121 0.372

 

The fastest methods are bolded. `Time.new.year` seems to be a good balance on performance if you are using either the latest MRI, Ruby 2.2 or JRuby at the time of this writing.

Further reading

I hope this helps you learn a little bit more about Ruby. It really is one of the best, most fun programming languages to work in. A good next step is to checkout the relevant Ruby standard library documentation on Date/Time classes at: