Just another WordPress.com site

Here’s a query to calculate the Age in Years, Months, Days, Hours and Minutes

declare @birth_day datetime
set @birth_day ='19660527 12:34:22'
select
 years,
 months,
 case
 when day(@birth_day)>day(getdate())
 then day(getdate())+
 datediff(day,@birth_day,dateadd(month,datediff(month,0,@birth_day)+1,0))-1
 else day(getdate())-day(@birth_day)
 end as days,
 datepart(hour,convert(varchar(10),dateadd(minute,minutes,0),108)) as hours,
 datepart(minute,convert(varchar(10),dateadd(minute,minutes,0),108)) as minutes
from
(
select
 years,
 datediff(month,dateadd(year,years,@birth_day),getdate())+
 case
 when day(getdate())>=day(@birth_day)
 then 0
 else -1 
 end as months,
 datediff(minute,convert(varchar(8),@birth_day,108),
 convert(varchar(8),getdate(),108)) as minutes
from
(
select
 datediff(year,@birth_day,getdate()) +
 case
 when month(getdate())>=month(@birth_day)
 then 0
 else -1
 end as years
) as t
) as t

In the query shown above, the inner query finds the year difference between current date and birth date. The case expression checks whether current month is greater than the month of birth date. If it is greater, a full year is completed, else the full year is not completed and one year is reduced from the result.

A similar check is done for month too. The outer parts calculate the hours and minutes.

OUTPUT

years           months          days            hours     minutes
44                    4                         5                        0                 0
About these ads

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

%d bloggers like this: