How to show current year in view?

Ruby on-RailsRuby on-Rails-3

Ruby on-Rails Problem Overview


Is there a function I can use to show the current year in a view? I have tried

<%= Time.now  %>

to try and show the time but this does not work for me.

Ruby on-Rails Solutions


Solution 1 - Ruby on-Rails

Solution 2 - Ruby on-Rails

I'd rather use Date class to get year than Time class (if you only need the Date, you don't need to consider hours, minutes and seconds).

<%= Date.today.year %>

c.f. http://ruby-doc.org/stdlib-2.1.0/libdoc/date/rdoc/Date.html#method-c-today

Solution 3 - Ruby on-Rails

I think the best way to get the current year considering application timezone is:

Date.current.year

Solution 4 - Ruby on-Rails

I like to use:

Time.zone.now.year

This takes into account the current timezone (incase you have overridden it for a particular user).

Solution 5 - Ruby on-Rails

Despite that it has already been answered, I thought it might come handy for those who want to look at benchmark results for all the suggested solutions.

require 'benchmark'

n = 500000
Benchmark.bm do |x|
  x.report { n.times do ; Date.today.year; end }
  x.report { n.times do ; Date.current.year; end }
  x.report { n.times do ; Time.current.year; end }
  x.report { n.times do ; Time.zone.now.year; end }
end

    user     system      total        real
0.680000   0.030000   0.710000 (  0.709078)
2.730000   0.010000   2.740000 (  2.735085)
3.340000   0.010000   3.350000 (  3.363586)
3.070000   0.000000   3.070000 (  3.082388)

Now, it may perhaps seem over the top for something as simple as that, however, from a simple optimisation perspective for a high throughput application, I will consider using Date.today.year

Said so, if your application is Time Zone sensitive, perhaps Date.current or Time.zone based methods are your best bet.

Check out this wonderful Railscast by Ryan on Time Zones

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionZakoffView Question on Stackoverflow
Solution 1 - Ruby on-RailsEmil AhlbäckView Answer on Stackoverflow
Solution 2 - Ruby on-RailsNaoyoshi AikawaView Answer on Stackoverflow
Solution 3 - Ruby on-RailsfreemanoidView Answer on Stackoverflow
Solution 4 - Ruby on-RailsstebooksView Answer on Stackoverflow
Solution 5 - Ruby on-RailsDarkfishView Answer on Stackoverflow