What would be the best way to calculate someone\'s age in years, months, and days in T-SQL (SQL Server 2000)?
The datediff
function doesn\'t handle year
declare @BirthDate datetime
declare @TotalYear int
declare @TotalMonths int
declare @TotalDays int
declare @TotalWeeks int
declare @TotalHours int
declare @TotalMinute int
declare @TotalSecond int
declare @CurrentDtTime datetime
set @BirthDate='1998/01/05 05:04:00' -- Set Your date here
set @TotalYear= FLOOR(DATEDIFF(DAY, @BirthDate, GETDATE()) / 365.25)
set @TotalMonths= FLOOR(DATEDIFF(DAY,DATEADD(year, @TotalYear,@BirthDate),GetDate()) / 30.436875E)
set @TotalDays= FLOOR(DATEDIFF(DAY, DATEADD(month, @TotalMonths,DATEADD(year,
@TotalYear,@BirthDate)), GETDATE()))
set @CurrentDtTime=CONVERT(datetime,CONVERT(varchar(50), DATEPART(year,
GetDate()))+'/' +CONVERT(varchar(50), DATEPART(MONTH, GetDate()))
+'/'+ CONVERT(varchar(50),DATEPART(DAY, GetDate()))+' '
+ CONVERT(varchar(50),DATEPART(HOUR, @BirthDate))+':'+
CONVERT(varchar(50),DATEPART(MINUTE, @BirthDate))+
':'+ CONVERT(varchar(50),DATEPART(Second, @BirthDate)))
set @TotalHours = DATEDIFF(hour, @CurrentDtTime, GETDATE())
if(@TotalHours < 0)
begin
set @TotalHours = DATEDIFF(hour,DATEADD(Day,-1, @CurrentDtTime), GETDATE())
set @TotalDays= @TotalDays -1
end
set @TotalMinute= DATEPART(MINUTE, GETDATE())-DATEPART(MINUTE, @BirthDate)
if(@TotalMinute < 0)
set @TotalMinute = DATEPART(MINUTE, DATEADD(hour,-1,GETDATE()))+(60-DATEPART(MINUTE,
@BirthDate))
set @TotalSecond= DATEPART(Second, GETDATE())-DATEPART(Second, @BirthDate)
Print 'Your age are'+ CHAR(13)
+ CONVERT(varchar(50), @TotalYear)+' Years, ' +
CONVERT(varchar(50),@TotalMonths) +' Months, ' +
CONVERT(varchar(50),@TotalDays)+' Days, ' +
CONVERT(varchar(50),@TotalHours)+' Hours, ' +
CONVERT(varchar(50),@TotalMinute)+' Minutes, ' +
CONVERT(varchar(50),@TotalSecond)+' Seconds. ' +char(13)+
'Your are born at day of week was - ' + CONVERT(varchar(50),DATENAME(dw ,
@BirthDate ))
+char(13)+char(13)+
+'Your Birthdate to till date your '+ CHAR(13)
+'Years - ' + CONVERT(varchar(50), FLOOR(DATEDIFF(DAY, @BirthDate, GETDATE()) /
365.25))
+' , Months - ' + CONVERT(varchar(50),DATEDIFF(MM,@BirthDate,getdate()))
+' , Weeks - ' + CONVERT(varchar(50),DATEDIFF(wk,@BirthDate,getdate()))
+' , Days - ' + CONVERT(varchar(50),DATEDIFF(dd,@BirthDate,getdate()))+char(13)+
+'Hours - ' + CONVERT(varchar(50),DATEDIFF(HH,@BirthDate,getdate()))
+' , Minutes - ' + CONVERT(varchar(50),DATEDIFF(mi,@BirthDate,getdate()))
+' , Seconds - ' + CONVERT(varchar(50),DATEDIFF(ss,@BirthDate,getdate()))
Output
Your age are
22 Years, 0 Months, 2 Days, 11 Hours, 30 Minutes, 16 Seconds.
Your are born at day of week was - Monday
Your Birthdate to till date your
Years - 22 , Months - 264 , Weeks - 1148 , Days - 8037
Hours - 192899 , Minutes - 11573970 , Seconds - 694438216