Img source: lynda.com

If you have a certain type of policy for not allowing users of all ages to use your services, or simply want to find the age of your users, then you can do it pretty easily and elegantly in Rails.

Craig Sheen has already written a topic on he addressed this issue, and I also wanted to write about it here.

He mentioned that he made several attempts (as it normally takes), until he finally managed to stumble upon a clear and elegant way.

He initially tried a very intuitive initiative:

Time.zone.now.year – date_of_birth.year

However, this does not take into consideration the months, nor the days of the months. For example, if your user is born on 28 November 1993, and you are executing the above on 2 February 2018, then you are actually making this user look many months older than he or she actually is, because the output of the above expression will be 25.

Craig mentioned that he Googled and found out the expression below, which accurately calculates the age, but seems a bit messy, and is hard to understand.

now = Time.zone.now.to_date

now.year – date_of_birth.year – ((now.month > date_of_birth.month || (now.month == date_of_birth.month && now.day >= date_of_birth.day)) ? 0 : 1)

He mentioned that he managed to reach the solution below, which is very elegant and accurate:

((Time.zone.now – date_of_birth.to_time) / 1.year.seconds).floor

This takes into consideration the timezone, and even the seconds. When the division is done, then this expression does a round down to the next smallest integer.  

That’s basically it.

There are many helper methods that are related to DateTime and Time in Rails, like the following, which make programming in Rails really pleasant and great:

DateTime.now.midnight

DateTime.now.beginning_of_day

Seeing all these simplified versions of doing things, It may not be of big surprise if we were to see new methods being added calculating someone’s age, or other information.