[SalesForce] How to determine age with AMPScript

I'm trying to figure out how to determine somebody's age in the form of years/months/days. For example, if I was born on 8/1/2014 and today is 9/15/2015 I would be 1 year, 1 month and 15 days old.

I know you can use DateDiff() to determine the difference in Days; but, I'm not sure how to convert that number into years/months/days. Any help is much appreciated.

Thanks everyone!

Best Answer

I was able to write an block of AMPScript to accomplish this. It is not the most elegant, but it works. The key is to use the AMPScript functions DatePart, DateParse, DateAdd, & DateDiff to calculate some key dates between now and the original date of birth (or any past date for that matter).

%%[ 
var @days, @years, @months
var @dob, @lastBDay
var @dt1 /* now */
var @dt2 /* lastBDay + months */
var @dt2 /* now - (lastDay + months)  */

set @dt1 = Now()
set @dob = "7/4/1976"
set @lastBDay = DateParse(concat(Datepart(@dt1,"year"),"-",Datepart(@dob,"month"),"-",Datepart(@dob,"day")))
if (datediff(@lastBDay,@dt1,"D") < 0) then
    set @lastBDay = DateParse(concat(Datepart(DateAdd(@dt1,-1,"Y"),"year"),"-",Datepart(@dob,"month"),"-",Datepart(@dob,"day")))
endif

set @years = DateDiff(@dob,@dt1,"Y")
set @months = DateDiff(@lastBDay,@dt1,"M")
set @dt2 = DateAdd(@lastBDay,@months,"M")
set @days = DateDiff(@dt2,@dt1, "D")

]%%
<pre>
input date = %%=v(@dob)=%%

years = %%=v(@years)=%%
months = %%=v(@months)=%%
days = %%=v(@days)=%%
</pre>

output:

input date = 7/4/1976

years = 39
months = 1
days = 23

p.s. Here's an online site you can use to validate against. http://www.timeanddate.com/date/durationresult.html?m1=7&d1=4&y1=1976&m2=8&d2=27&y2=2015

Related Topic