Age of a Person = Given date - Date of birth. Ron's Date of Birth = July 25, 1985. Given date = January 28, 2021. Years' Difference = 2020 - 1985 = 35 years.
int age = (int) ((DateTime. Now - bday). TotalDays/365.242199);
Age is extracted from Date_of_birth column using difftime() functions in roundabout way by extracting the number of weeks between date of birth and current date and dividing by 52.25, as shown below.
I know I'm late to the party here, but the accepted answer will break horribly when trying to work out the age of someone born on the 29th February on a leap year. This is because the call to birthday.to_date.change(:year => now.year)
creates an invalid date.
I used the following code instead:
require 'date'
def age(dob)
now = Time.now.utc.to_date
now.year - dob.year - ((now.month > dob.month || (now.month == dob.month && now.day >= dob.day)) ? 0 : 1)
end
I've found this solution to work well and be readable for other people:
age = Date.today.year - birthday.year
age -= 1 if Date.today < birthday + age.years #for days before birthday
Easy and you don't need to worry about handling leap year and such.
Use this:
def age
now = Time.now.utc.to_date
now.year - birthday.year - (birthday.to_date.change(:year => now.year) > now ? 1 : 0)
end
One liner in Ruby on Rails (ActiveSupport). Handles leap years, leap seconds and all.
def age(birthday)
(Time.now.to_s(:number).to_i - birthday.to_time.to_s(:number).to_i)/10e9.to_i
end
Logic from here - Calculate age in C#
Assuming both dates are in same timezone, if not call utc()
before to_s()
on both.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With