Get a list of mondays between date range - tsql

I need to show N records with each record being 1 weeks worth of summarized data. One of the inputs will be a date range.
Since each week should start with monday, I want to get a list of all the monday dates in the date range. Any suggestions to get that?
Note: This has to run on SQL 2005
declare #dt datetime
SET #dt = '2010-01-01'
declare #dtEnd datetime
SET #dtEnd = '2010-12-04'
DECLARE #day AS NVARCHAR(30)
WHILE (#dt < #dtEnd) BEGIN
-- insert into table(datefield)
-- values(#dt)
SET #day = UPPER(DATENAME(weekday,#dt))
IF #day = 'MONDAY'
--PRINT 'date is: ' + CAST(#dt AS VARCHAR(30))
BEGIN
PRINT 'date is: ' + CAST(#dt AS VARCHAR(30)) + ' ' + #day
END
SET #dt = DATEADD(day, 1, #dt)
END

The code you show seems to work, but it can be made more efficient. The code I show below will calculate the first Monday on or after the start date. Then it is used in the same loop but we simply add 7 days each time through the loop.
declare #dt datetime,
#dtEnd datetime
SET #dt = '2010-01-01'
SET #dtEnd = '2010-12-04'
Set #dt = DateAdd(Day, 7 - DateDiff(Day, 0, #dt) % 7, #dt)
WHILE (#dt < #dtEnd) BEGIN
PRINT 'date is: ' + CAST(#dt AS VARCHAR(30)) + ' ' + DateName(Weekday, #dt)
SET #dt = DATEADD(day, 7, #dt)
END
One thing I notice about your code is that you are using DateName, which works ok for displaying the weekday name, but not so good for making decisions (like you are doing). The problem with DateName is that it uses the language setting of the currently logged in user.
The following code shows this behavior.
set language 'spanish'
Select DateName(Weekday, GetDate())
set language 'us_english'
Select DateName(Weekday, GetDate())
Basically, if the language of a user was set to spanish, your code would fail but mine would not. Mine works because it uses the fact that January 1, 1900 was a Monday. It calculates the number of days and takes a mod of that and uses that mod to add the correct number of days. Since January 1, 1900 will always be a Monday, and we are not using the DateName function, this code will work without regard to the language setting.

SELECT * from table t
WHERE t.date between 'startDate' and 'endDate'
AND (SELECT DATEPART(dw,t.StudyDate))=2

Related

Convert Excel formula (using Date and subtraction) into T-SQL

I am trying to write this Excel formula into T-SQL (to write a function).
Expected output is 0.71944444, but currently my output (using T-SQL) is 24.0000.
I am not sure why we have to add a day to same date and subtract the same date.
Bottom is a screenshot from Excel:
This is what I have so far in T-SQL:
CREATE FUNCTION [dbo].[fn_0921] (
#Punch_Start nvarchar(max)
)
RETURNS decimal(36, 8) AS
BEGIN
DECLARE #return_value nvarchar(max);
SET #return_value =
DATEDIFF(
MINUTE, CAST(#Punch_Start AS datetime2),
(
dateadd(
day, 1, CAST(#Punch_Start AS datetime2)
)
)
)
/ (60.0)
RETURN #return_value
END;
Thanks for help.
The Excel formula is returning the difference between the datetime in cell K4 & the start of the next day (i.e. 7/26/2021 00:00) as a fraction of a whole day. The following is the equivalent in T-SQL:
DECLARE #Punch_Start datetime2 = '7/25/2021 06:44';
SELECT DATEDIFF(
MINUTE,
#Punch_Start,
CAST(
CAST(
DATEADD(DAY, 1, #Punch_Start)
AS date) -- Add 1 day to #Punch_Start & cast as date to remove the time component - this is the start of the next day
AS datetime2) -- Cast back to datetime2 to get the difference in minutes
) / 1440.; -- Divide the difference in minutes by the number of minutes in a day (60 minutes per hour, 24 hours per day) to get the difference as a fraction of a day
This can probably help you:
DECLARE #date DATETIME2 = '2021-07-25 06:44'
DECLARE #seconds INT = DATEDIFF(second, CAST(#date AS date), #date)
DECLARE #secondsFromEnd FLOAT = 86400 - #seconds
SELECT #secondsFromEnd / 86400

How do I use a calculated value within a DATEFROMPARTS in SQL

I need a calculated month value within DATEFROMPARTS function. The month has to be seven month prior to CURRENT_TIMESTAMP month.
This is what I tried:
DATEFROMPARTS(Year(CURRENT_TIMESTAMP), Month(CURRENT_TIMESTAMP)-7, 1) as SevenMoAgo;
I will eventually use this in the following expression where '12-01-2018' is:
where RECORDED_SERVICE_STARTTIME > ='12-01-2018'
I later used
declare #CurMo AS INT;
declare #MonPri7 AS INT;
set #CurMo = Month(CURRENT_TIMESTAMP);
set #MonPri7 = (#CurMo -7);
Datefromparts(Year(CURRENT_TIMESTAMP), #MonPri7, 1) as SevenMoAgo;
This also did not work.
I get the following error message:
"Cannot construct data type date, some of the arguments have values which are not valid."
For the second code I get:
Msg 102, Level 15, State 1, Line 8
Incorrect syntax near 'Datefromparts'.
Try this...
SELECT DATEADD(MONTH, DATEDIFF(MONTH, 0, CURRENT_TIMESTAMP) - 7, 0)
Let me explain. First off, we need to understand that SQL Server interprets 0 as 1900-01-01 as shown by the following DATEPART functions.
SELECT DATEPART(YEAR, 0) AS Year
, DATEPART(MONTH, 0) AS Month
, DATEPART(DAY, 0) AS Day;
Which returns...
Year Month Day
----------- ----------- -----------
1900 1 1
Therefore, my SQL could be rewritten as...
SELECT DATEADD(MONTH, DATEDIFF(MONTH, '1900-01-01', CURRENT_TIMESTAMP) - 7, '1900-01-01')
Now perhaps it is a little easier to see what is going on here. The DATEDIFF function returns the number number of months between 1900-01-01 and today (CURRENT_TIMESTAMP) which is 1434.
SELECT DATEADD(MONTH, 1434 - 7, '1900-01-01')
Then we subtract 7 from 1434 which is 1427 and add that many months back to 1900-01-01.
SELECT DATEADD(MONTH, 1427, '1900-01-01')
Which yields 2018-12-01.
The reason is #MonPri7 is equal to ZERO when you say (#CurMo -7)
There are many different ways to calculate it, but if you want to fix your logic, you should use this:
declare #CurMo AS INT;
declare #MonPri7 AS INT;
set #CurMo = Month(CURRENT_TIMESTAMP);
set #MonPri7 = (#CurMo -7);
declare #Y int = Year(CURRENT_TIMESTAMP) -- <-- This is new variable
-- if 7 months ago is ZERO then you should go back to prev year December
if #MonPri7 = 0
begin
set #MonPri7 = 12
set #Y = #Y - 1
end
Edit:
declare #SevenMonthsAgo datetime;
select #SevenMonthsAgo = Datefromparts(#Y, #MonPri7, 1);
SELECT yourfields
FROM yourtable
where RECORDED_SERVICE_STARTTIME > = '01-01-2019' and
RECORDED_SERVICE_STARTTIME > = #SevenMonthsAgo

Functions to convert dates between local time and UTC time by considering US day light savings time

I would like to contribute my codes related to the date conversion between local time and UTC time for both current and historical dates, including day light savings time consideration. I reviewed some recent postings but could not find the solution I am looking for so I summarize the solutions I found to develop my own solution. I am running my codes in SQL Server 2008R2. Test cases are provided as comments before each function. Feel free to check out the Credits section for related postings, try out my codes, and let me know if I miss anything. Thanks.
-- Test 1: select dbo.fn_isDayLightSavings(CAST('2014-01-01' AS DATE)), expect 0
-- Test 2: select dbo.fn_isDayLightSavings(CAST('2014-04-14' AS DATE)), expect 1
IF OBJECT_ID(N'fn_isDayLightSavings') IS NOT NULL AND OBJECTPROPERTY(OBJECT_ID(N'fn_isDayLightSavings'),'IsScalarFunction') = 1
DROP FUNCTION fn_isDayLightSavings;
GO
CREATE FUNCTION fn_isDayLightSavings (#dt AS DATETIME)
RETURNS TINYINT
AS
BEGIN
DECLARE #rtn TINYINT, #year INT, #dtsStartMonth DATETIME, #dtsEndMonth DATETIME, #dstStart DATETIME, #dstEnd DATETIME;
SET #year = DATEPART(YEAR, #dt);
-- In year 2007, US day light savings period changes from Apr-Oct to Mar-Nov.
if #year < 2007
BEGIN
-- Last Sunday of April at 2 AM
SET #dtsStartMonth = DATEADD(MONTH, 4, DATEADD(YEAR, #year - 1900, 0));
SET #dstStart = DATEADD(HOUR, 2, DATEADD(day, -(DATEPART(dw, #dtsStartMonth) - 1), #dtsStartMonth));
-- Last Sunday of October at 2 AM
SET #dtsEndMonth = DATEADD(MONTH, 10, DATEADD(YEAR, #year - 1900, 0));
SET #dstEnd = DATEADD(HOUR, 2, DATEADD(day, -(DATEPART(dw, #dtsEndMonth) - 1), #dtsEndMonth));
END
else
BEGIN
-- 2nd Sunday of March at 2 AM
SET #dtsStartMonth = DATEADD(MONTH, 2, DATEADD(YEAR, #year - 1900, 0));
SET #dstStart = DATEADD(HOUR, 2, DATEADD(day, ((15 - DATEPART(dw, #dtsStartMonth)) % 7) + 7, #dtsStartMonth));
-- 1st Sunday of November at 2 AM
SET #dtsEndMonth = DATEADD(MONTH, 10, DATEADD(YEAR, #year - 1900, 0));
SET #dstEnd = DATEADD(HOUR, 2, DATEADD(day, ((8 - DATEPART(dw, #dtsEndMonth)) % 7) + 7, #dtsEndMonth));
END
if #dt BETWEEN #dstStart AND #dstEnd SET #rtn=1 ELSE SET #rtn=0;
RETURN #rtn;
END
GO
-- Test 1: select dbo.fn_DateTime2UTC(CAST('2014-01-01 01:00:00' AS DATETIME), 0), expect '2014-01-01 07:00:00.000'
-- Test 2: select dbo.fn_DateTime2UTC(CAST('2014-01-01 01:00:00' AS DATETIME), 1), expect '2013-01-01 07:00:00.000'
-- Test 3: select dbo.fn_DateTime2UTC(CAST('2014-05-01 01:00:00' AS DATETIME), 0), expect '2014-05-01 06:00:00.000'
-- Test 4: select dbo.fn_DateTime2UTC(CAST('2014-05-01 01:00:00' AS DATETIME), 1), expect '2014-05-01 07:00:00.000'
IF OBJECT_ID(N'fn_DateTime2UTC') IS NOT NULL AND OBJECTPROPERTY(OBJECT_ID(N'fn_DateTime2UTC'),'IsScalarFunction') = 1
DROP FUNCTION fn_DateTime2UTC;
GO
CREATE FUNCTION fn_DateTime2UTC (#dt AS DATETIME, #ignoreDST AS TINYINT = 0)
-- do CAST(? AS DATETIMEOFFSET), if need datetimeoffset type
RETURNS DATETIME
AS
BEGIN
DECLARE #tzOffset INT, #utcDt DATETIME;
-- Get current time zone offset in minutes
SET #tzOffset = DATEPART(TZoffset, SYSDATETIMEOFFSET()) +
(CASE WHEN dbo.fn_isDayLightSavings(#dt)=1 THEN 60 ELSE 0 END);
if dbo.fn_isDayLightSavings(#dt)=0
set #utcDt = DATEADD(MINUTE, -#tzOffset, #dt);
else if #ignoreDST=0
set #utcDt = DATEADD(MINUTE, -#tzOffset, #dt);
else
set #utcDt = DATEADD(MINUTE, -#tzOffset+60, #dt);
return #utcDt;
END
GO
-- Test 1: select dbo.fn_UTC2DateTime(CAST('2014-01-01 07:00:00.000' AS DATETIME), 0), expect '2014-01-01 01:00:00'
-- Test 2: select dbo.fn_UTC2DateTime(CAST('2013-01-01 07:00:00.000' AS DATETIME), 1), expect '2014-01-01 01:00:00'
-- Test 3: select dbo.fn_UTC2DateTime(CAST('2014-05-01 06:00:00.000' AS DATETIME), 0), expect '2014-05-01 01:00:00'
-- Test 4: select dbo.fn_UTC2DateTime(CAST('2014-05-01 07:00:00.000' AS DATETIME), 1), expect '2014-05-01 01:00:00'
IF OBJECT_ID(N'fn_UTC2DateTime') IS NOT NULL AND OBJECTPROPERTY(OBJECT_ID(N'fn_UTC2DateTime'),'IsScalarFunction') = 1
DROP FUNCTION fn_UTC2DateTime;
GO
CREATE FUNCTION fn_UTC2DateTime (#utcDt AS DATETIME, #ignoreDST AS TINYINT = 0)
RETURNS DATETIME
AS
BEGIN
DECLARE #tzOffset INT, #dt DATETIME;
-- Get current time zone offset in minutes
SET #tzOffset = DATEPART(TZoffset, SYSDATETIMEOFFSET()) +
(CASE WHEN dbo.fn_isDayLightSavings(#utcDt)=1 THEN 60 ELSE 0 END);
if dbo.fn_isDayLightSavings(#utcDt)=0
set #dt = DATEADD(MINUTE, #tzOffset, #utcDt);
else if #ignoreDST=0
set #dt = DATEADD(MINUTE, #tzOffset, #utcDt);
else
set #dt = DATEADD(MINUTE, #tzOffset-60, #utcDt);
return #dt;
END
GO
-- Test 1: select dbo.fn_UTC2DateTimeOffset(CAST('2014-01-01 07:00:00.000' AS DATETIME), 0), expect '2014-01-01 01:00:00.0000000 -06:00'
-- Test 2: select dbo.fn_UTC2DateTimeOffset(CAST('2013-01-01 07:00:00.000' AS DATETIME), 1), expect '2014-01-01 01:00:00.0000000 -06:00'
-- Test 3: select dbo.fn_UTC2DateTimeOffset(CAST('2014-05-01 06:00:00.000' AS DATETIME), 0), expect '2014-05-01 01:00:00.0000000 -05:00'
-- Test 4: select dbo.fn_UTC2DateTimeOffset(CAST('2014-05-01 07:00:00.000' AS DATETIME), 1), expect '2014-05-01 00:00:00.0000000 -06:00'
IF OBJECT_ID(N'fn_UTC2DateTimeOffset') IS NOT NULL AND OBJECTPROPERTY(OBJECT_ID(N'fn_UTC2DateTimeOffset'),'IsScalarFunction') = 1
DROP FUNCTION fn_UTC2DateTimeOffset;
GO
CREATE FUNCTION fn_UTC2DateTimeOffset (#utcDt AS DATETIME, #ignoreDST TINYINT = 0)
RETURNS DATETIMEOFFSET
AS
BEGIN
DECLARE #tzOffset INT, #dt DATETIMEOFFSET;
-- Get current time zone offset in minutes
SET #tzOffset = DATEPART(TZoffset, SYSDATETIMEOFFSET()) +
(CASE WHEN dbo.fn_isDayLightSavings(#utcDt)=1 THEN 60 ELSE 0 END);
if dbo.fn_isDayLightSavings(#utcDt)=0
set #dt = SWITCHOFFSET(CAST(#utcDt AS DATETIMEOFFSET), #tzOffset);
else if #ignoreDST=0
set #dt = SWITCHOFFSET(CAST(#utcDt AS DATETIMEOFFSET), #tzOffset);
else
set #dt = SWITCHOFFSET(CAST(#utcDt AS DATETIMEOFFSET), #tzOffset-60);
return #dt;
END
GO
-- Credits:
-- Determination of day light savings start and end time, Jamie F., 11/1/2013
-- (http://stackoverflow.com/questions/19732896/how-to-create-daylight-savings-time-start-and-end-function-in-sql-server)
-- Day light savings time calendar, USNO
-- (http://aa.usno.navy.mil/faq/docs/daylight_time.php)
-- Time zone offset, Microsoft
-- (http://msdn.microsoft.com/en-us/library/ms174420.aspx)
-- Local system date time with time zone, Robert Cantor, 12/7/2013
-- (http://stackoverflow.com/questions/1205142/tsql-how-to-convert-local-time-to-utc-sqlserver2008)
-- Convert date with time zone and day light savings, Eric Z Beard, 8/24/2008
-- (http://stackoverflow.com/questions/24797/effectively-converting-dates-between-utc-and-local-ie-pst-time-in-sql-2005#25073)
Kudos to you for assembling that knowledge into one place. Assuming it is accurate, it's easy to pick up and use immediately.
However, the trouble is that without an extensive set of unit tests you can't be sure of accuracy.
Might I suggest the best option for date/time conversions would be to use an existing highly tested open source library such as http://nodatime.org/. Date/time conversions have so many intracacies and details that could not possibly be contained in a few dozen lines of SQL code.
nodatime is a .NET library that should easily be accessible via the SQL Server CLR user-defined functions feature.

TSQL need to return last day of month only, how do I drop year, month & time?

I am writing a function in T-SQL returning the last day of the month regardless of the date input.
Here is my code:
Alter Function dbo.FN_Get_Last_Day_in_Month2
(#FN_InputDt Datetime)
Returns smalldatetime
as
Begin
Declare #Result smalldatetime
Set #Result =
case when #FN_InputDt <> 01-01-1900 then
DATEADD(m, DATEDIFF(M, 0,#FN_InputDt)+1, -1)
Else 0 End
Return #Result
End
The code is not working correctly, here is a test that shows the bad behavior:
SELECT dbo.fn_get_last_day_in_month (07-05-2010)
Here is the (incorrect) result:
2010-07-31 00:00:00
What is 07-05-2010...May 7th or July 5th? You need to use a safe date format, take a look at Setting a standard DateFormat for SQL Server
example from How to find the first and last days in years, months etc
DECLARE #d DATETIME
SET #d = '20100705' -- notice ISO format
SELECT
DATEADD(yy, DATEDIFF(yy, 0, #d), 0) AS FirstDayOfYear,
DATEADD(yy, DATEDIFF(yy, 0, #d)+1, -1) AS LastDayOfYear,
DATEADD(qq, DATEDIFF(qq, 0, #d), 0) AS FirstDayOfQuarter,
DATEADD(qq, DATEDIFF(qq, 0, #d)+1, -1) AS LastDayOfQuarter,
DATEADD(mm, DATEDIFF(mm, 0, #d), 0) AS FirstDayOfMonth,
DATEADD(mm, DATEDIFF(mm, 0, #d)+1, -1) AS LastDayOfMonth,
#d - DATEDIFF(dd, ##DATEFIRST - 1, #d) % 7 AS FirstDayOfWeek,
#d - DATEDIFF(dd, ##DATEFIRST - 1, #d) % 7 + 6 AS LastDayOfWeek
for just the day use day or datepart
select DAY(getdate()),
DATEPART(dd,GETDATE())
Cast the return value to a SQL datetime type, and then call the "DAY" function to get the day in as an integer. See the function reference here:
http://msdn.microsoft.com/en-us/library/ms176052.aspx
Not sure which database you're using, but this should be a standard function across all databases.
I'd return a DATETIME, I've had trouble with SMALLDATETIME in the past.
DECLARE #Result DATETIME
SET #Result = DATEADD(m , 1, #FN_Input);
RETURN CAST(FLOOR(CAST(DATEADD(d, DATEPART(d, #Result) * -1, #Result) AS FLOAT)) AS DATETIME)
Also, I think you may be a victim of SQL's complete disregard of date formatting. Always, always, always, when typing a string into test a SQL function use the following format;
'05 Jul 2010'
Your function probably works but it interpreted your date as 5th July - not 7th May.
DECLARE #date DATETIME = '20130624';
SELECT Day(EOMONTH ( #date )) AS LastDay;
GO

How to calculate age in T-SQL with years, months, and days

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 boundaries well, plus getting the months and days separate will be a bear. I know I can do it on the client side relatively easily, but I'd like to have it done in my stored procedure.
Here is some T-SQL that gives you the number of years, months, and days since the day specified in #date. It takes into account the fact that DATEDIFF() computes the difference without considering what month or day it is (so the month diff between 8/31 and 9/1 is 1 month) and handles that with a case statement that decrements the result where appropriate.
DECLARE #date datetime, #tmpdate datetime, #years int, #months int, #days int
SELECT #date = '2/29/04'
SELECT #tmpdate = #date
SELECT #years = DATEDIFF(yy, #tmpdate, GETDATE()) - CASE WHEN (MONTH(#date) > MONTH(GETDATE())) OR (MONTH(#date) = MONTH(GETDATE()) AND DAY(#date) > DAY(GETDATE())) THEN 1 ELSE 0 END
SELECT #tmpdate = DATEADD(yy, #years, #tmpdate)
SELECT #months = DATEDIFF(m, #tmpdate, GETDATE()) - CASE WHEN DAY(#date) > DAY(GETDATE()) THEN 1 ELSE 0 END
SELECT #tmpdate = DATEADD(m, #months, #tmpdate)
SELECT #days = DATEDIFF(d, #tmpdate, GETDATE())
SELECT #years, #months, #days
Try this...
SELECT CASE WHEN
(DATEADD(year,DATEDIFF(year, #datestart ,#dateend) , #datestart) > #dateend)
THEN DATEDIFF(year, #datestart ,#dateend) -1
ELSE DATEDIFF(year, #datestart ,#dateend)
END
Basically the "DateDiff( year...", gives you the age the person will turn this year, so i have just add a case statement to say, if they have not had a birthday yet this year, then subtract 1 year, else return the value.
Simple way to get age as text is as below:
Select cast((DATEDIFF(m, date_of_birth, GETDATE())/12) as varchar) + ' Y & ' +
cast((DATEDIFF(m, date_of_birth, GETDATE())%12) as varchar) + ' M' as Age
Results Format will be:
**63 Y & 2 M**
Implemented by arithmetic with ISO formatted date.
declare #now date,#dob date, #now_i int,#dob_i int, #days_in_birth_month int
declare #years int, #months int, #days int
set #now = '2013-02-28'
set #dob = '2012-02-29' -- Date of Birth
set #now_i = convert(varchar(8),#now,112) -- iso formatted: 20130228
set #dob_i = convert(varchar(8),#dob,112) -- iso formatted: 20120229
set #years = ( #now_i - #dob_i)/10000
-- (20130228 - 20120229)/10000 = 0 years
set #months =(1200 + (month(#now)- month(#dob))*100 + day(#now) - day(#dob))/100 %12
-- (1200 + 0228 - 0229)/100 % 12 = 11 months
set #days_in_birth_month = day(dateadd(d,-1,left(convert(varchar(8),dateadd(m,1,#dob),112),6)+'01'))
set #days = (sign(day(#now) - day(#dob))+1)/2 * (day(#now) - day(#dob))
+ (sign(day(#dob) - day(#now))+1)/2 * (#days_in_birth_month - day(#dob) + day(#now))
-- ( (-1+1)/2*(28 - 29) + (1+1)/2*(29 - 29 + 28))
-- Explain: if the days of now is bigger than the days of birth, then diff the two days
-- else add the days of now and the distance from the date of birth to the end of the birth month
select #years,#months,#days -- 0, 11, 28
Test Cases
The approach of days is different from the accepted answer, the differences shown in the comments below:
dob now years months days
2012-02-29 2013-02-28 0 11 28 --Days will be 30 if calculated by the approach in accepted answer.
2012-02-29 2016-02-28 3 11 28 --Days will be 31 if calculated by the approach in accepted answer, since the day of birth will be changed to 28 from 29 after dateadd by years.
2012-02-29 2016-03-31 4 1 2
2012-01-30 2016-02-29 4 0 30
2012-01-30 2016-03-01 4 1 2 --Days will be 1 if calculated by the approach in accepted answer, since the day of birth will be changed to 30 from 29 after dateadd by years.
2011-12-30 2016-02-29 4 1 30
An short version of Days by case statement:
set #days = CASE WHEN day(#now) >= day(#dob) THEN day(#now) - day(#dob)
ELSE #days_in_birth_month - day(#dob) + day(#now) END
If you want the age of years and months only, it could be simpler
set #years = ( #now_i/100 - #dob_i/100)/100
set #months =(12 + month(#now) - month(#dob))%12
select #years,#months -- 1, 0
NOTE: A very useful link of SQL Server Date Formats
Here is a (slightly) simpler version:
CREATE PROCEDURE dbo.CalculateAge
#dayOfBirth datetime
AS
DECLARE #today datetime, #thisYearBirthDay datetime
DECLARE #years int, #months int, #days int
SELECT #today = GETDATE()
SELECT #thisYearBirthDay = DATEADD(year, DATEDIFF(year, #dayOfBirth, #today), #dayOfBirth)
SELECT #years = DATEDIFF(year, #dayOfBirth, #today) - (CASE WHEN #thisYearBirthDay > #today THEN 1 ELSE 0 END)
SELECT #months = MONTH(#today - #thisYearBirthDay) - 1
SELECT #days = DAY(#today - #thisYearBirthDay) - 1
SELECT #years, #months, #days
GO
The same sort of thing as a function.
create function [dbo].[Age](#dayOfBirth datetime, #today datetime)
RETURNS varchar(100)
AS
Begin
DECLARE #thisYearBirthDay datetime
DECLARE #years int, #months int, #days int
set #thisYearBirthDay = DATEADD(year, DATEDIFF(year, #dayOfBirth, #today), #dayOfBirth)
set #years = DATEDIFF(year, #dayOfBirth, #today) - (CASE WHEN #thisYearBirthDay > #today THEN 1 ELSE 0 END)
set #months = MONTH(#today - #thisYearBirthDay) - 1
set #days = DAY(#today - #thisYearBirthDay) - 1
return cast(#years as varchar(2)) + ' years,' + cast(#months as varchar(2)) + ' months,' + cast(#days as varchar(3)) + ' days'
end
create procedure getDatedifference
(
#startdate datetime,
#enddate datetime
)
as
begin
declare #monthToShow int
declare #dayToShow int
--set #startdate='01/21/1934'
--set #enddate=getdate()
if (DAY(#startdate) > DAY(#enddate))
begin
set #dayToShow=0
if (month(#startdate) > month(#enddate))
begin
set #monthToShow= (12-month(#startdate)+ month(#enddate)-1)
end
else if (month(#startdate) < month(#enddate))
begin
set #monthToShow= ((month(#enddate)-month(#startdate))-1)
end
else
begin
set #monthToShow= 11
end
-- set #monthToShow= convert(int, DATEDIFF(mm,0,DATEADD(dd,DATEDIFF(dd,0,#enddate)- DATEDIFF(dd,0,#startdate),0)))-((convert(int,FLOOR(DATEDIFF(day, #startdate, #enddate) / 365.25))*12))-1
if(#monthToShow<0)
begin
set #monthToShow=0
end
declare #amonthbefore integer
set #amonthbefore=Month(#enddate)-1
if(#amonthbefore=0)
begin
set #amonthbefore=12
end
if (#amonthbefore in(1,3,5,7,8,10,12))
begin
set #dayToShow=31-DAY(#startdate)+DAY(#enddate)
end
if (#amonthbefore=2)
begin
IF (YEAR( #enddate ) % 4 = 0 AND YEAR( #enddate ) % 100 != 0) OR YEAR( #enddate ) % 400 = 0
begin
set #dayToShow=29-DAY(#startdate)+DAY(#enddate)
end
else
begin
set #dayToShow=28-DAY(#startdate)+DAY(#enddate)
end
end
if (#amonthbefore in (4,6,9,11))
begin
set #dayToShow=30-DAY(#startdate)+DAY(#enddate)
end
end
else
begin
--set #monthToShow=convert(int, DATEDIFF(mm,0,DATEADD(dd,DATEDIFF(dd,0,#enddate)- DATEDIFF(dd,0,#startdate),0)))-((convert(int,FLOOR(DATEDIFF(day, #startdate, #enddate) / 365.25))*12))
if (month(#enddate)< month(#startdate))
begin
set #monthToShow=12+(month(#enddate)-month(#startdate))
end
else
begin
set #monthToShow= (month(#enddate)-month(#startdate))
end
set #dayToShow=DAY(#enddate)-DAY(#startdate)
end
SELECT
FLOOR(DATEDIFF(day, #startdate, #enddate) / 365.25) as [yearToShow],
#monthToShow as monthToShow ,#dayToShow as dayToShow ,
convert(varchar,FLOOR(DATEDIFF(day, #startdate, #enddate) / 365.25)) +' Year ' + convert(varchar,#monthToShow) +' months '+convert(varchar,#dayToShow)+' days ' as age
return
end
I use this Function I modified (the Days part) From #Dane answer: https://stackoverflow.com/a/57720/2097023
CREATE FUNCTION dbo.EdadAMD
(
#FECHA DATETIME
)
RETURNS NVARCHAR(10)
AS
BEGIN
DECLARE
#tmpdate DATETIME
, #years INT
, #months INT
, #days INT
, #EdadAMD NVARCHAR(10);
SELECT #tmpdate = #FECHA;
SELECT #years = DATEDIFF(yy, #tmpdate, GETDATE()) - CASE
WHEN (MONTH(#FECHA) > MONTH(GETDATE()))
OR (
MONTH(#FECHA) = MONTH(GETDATE())
AND DAY(#FECHA) > DAY(GETDATE())
) THEN
1
ELSE
0
END;
SELECT #tmpdate = DATEADD(yy, #years, #tmpdate);
SELECT #months = DATEDIFF(m, #tmpdate, GETDATE()) - CASE
WHEN DAY(#FECHA) > DAY(GETDATE()) THEN
1
ELSE
0
END;
SELECT #tmpdate = DATEADD(m, #months, #tmpdate);
IF MONTH(#FECHA) = MONTH(GETDATE())
AND DAY(#FECHA) > DAY(GETDATE())
SELECT #days =
DAY(EOMONTH(GETDATE(), -1)) - (DAY(#FECHA) - DAY(GETDATE()));
ELSE
SELECT #days = DATEDIFF(d, #tmpdate, GETDATE());
SELECT #EdadAMD = CONCAT(#years, 'a', #months, 'm', #days, 'd');
RETURN #EdadAMD;
END;
GO
It works pretty well.
I've seen the question several times with results outputting Years, Month, Days but never a numeric / decimal result. (At least not one that doesn't round incorrectly).
I welcome feedback on this function. Might not still need a little adjusting.
-- Input to the function is two dates.
-- Output is the numeric number of years between the two dates in Decimal(7,4) format.
-- Output is always always a possitive number.
-- NOTE:Output does not handle if difference is greater than 999.9999
-- Logic is based on three steps.
-- 1) Is the difference less than 1 year (0.5000, 0.3333, 0.6667, ect.)
-- 2) Is the difference exactly a whole number of years (1,2,3, ect.)
-- 3) (Else)...The difference is years and some number of days. (1.5000, 2.3333, 7.6667, ect.)
CREATE Function [dbo].[F_Get_Actual_Age](#pi_date1 datetime,#pi_date2 datetime)
RETURNS Numeric(7,4)
AS
BEGIN
Declare
#l_tmp_date DATETIME
,#l_days1 DECIMAL(9,6)
,#l_days2 DECIMAL(9,6)
,#l_result DECIMAL(10,6)
,#l_years DECIMAL(7,4)
--Check to make sure there is a date for both inputs
IF #pi_date1 IS NOT NULL and #pi_date2 IS NOT NULL
BEGIN
IF #pi_date1 > #pi_date2 --Make sure the "older" date is in #pi_date1
BEGIN
SET #l_tmp_date = #pi_date2
SET #pi_date2 = #Pi_date1
SET #pi_date1 = #l_tmp_date
END
--Check #1 If date1 + 1 year is greater than date2, difference must be less than 1 year
IF DATEADD(YYYY,1,#pi_date1) > #pi_date2
BEGIN
--How many days between the two dates (numerator)
SET #l_days1 = DATEDIFF(dd,#pi_date1, #pi_date2)
--subtract 1 year from date2 and calculate days bewteen it and date2
--This is to get the denominator and accounts for leap year (365 or 366 days)
SET #l_days2 = DATEDIFF(dd,dateadd(yyyy,-1,#pi_date2),#pi_date2)
SET #l_years = #l_days1 / #l_days2 -- Do the math
END
ELSE
--Check #2 Are the dates an exact number of years apart.
--Calculate years bewteen date1 and date2, then add the years to date1, compare dates to see if exactly the same.
IF DATEADD(YYYY,DATEDIFF(YYYY,#pi_date1,#pi_date2),#pi_date1) = #pi_date2
SET #l_years = DATEDIFF(YYYY,#pi_date1, #pi_date2) --AS Years, 'Exactly even Years' AS Msg
ELSE
BEGIN
--Check #3 The rest of the cases.
--Check if datediff, returning years, over or under states the years difference
SET #l_years = DATEDIFF(YYYY,#pi_date1, #pi_date2)
IF DATEADD(YYYY,#l_years,#pi_date1) > #pi_date2
SET #l_years = #l_years -1
--use basicly same logic as in check #1
SET #l_days1 = DATEDIFF(dd,DATEADD(YYYY,#l_years,#pi_date1), #pi_date2)
SET #l_days2 = DATEDIFF(dd,dateadd(yyyy,-1,#pi_date2),#pi_date2)
SET #l_years = #l_years + #l_days1 / #l_days2
--SELECT #l_years AS Years, 'Years Plus' AS Msg
END
END
ELSE
SET #l_years = 0 --If either date was null
RETURN #l_Years --Return the result as decimal(7,4)
END
`
Quite Old question, but I want to share what I have done to calculate age
Declare #BirthDate As DateTime
Set #BirthDate = '1994-11-02'
SELECT DATEDIFF(YEAR,#BirthDate,GETDATE()) - (CASE
WHEN MONTH(#BirthDate)> MONTH(GETDATE()) THEN 1
WHEN MONTH(#BirthDate)= MONTH(GETDATE()) AND DAY(#BirthDate) > DAY(GETDATE()) THEN 1
Else 0 END)
Are you trying to calculate the total days/months/years of an age? do you have a starting date? Or are you trying to dissect it (ex: 24 years, 1 month, 29 days)?
If you have a start date that you're working with, datediff will output the total days/months/years with the following commands:
Select DateDiff(d,'1984-07-12','2008-09-11')
Select DateDiff(m,'1984-07-12','2008-09-11')
Select DateDiff(yyyy,'1984-07-12','2008-09-11')
with the respective outputs being (8827/290/24).
Now, if you wanted to do the dissection method, you'd have to subtract the number of years in days (days - 365*years), and then do further math on that to get the months, etc.
Here is SQL code that gives you the number of years, months, and days since the sysdate.
Enter value for input_birth_date this format(dd_mon_yy). note: input same value(birth date) for years, months & days such as 01-mar-85
select trunc((sysdate -to_date('&input_birth_date_dd_mon_yy'))/365) years,
trunc(mod(( sysdate -to_date('&input_birth_date_dd_mon_yy'))/365,1)*12) months,
trunc((mod((mod((sysdate -to_date('&input_birth_date_dd_mon_yy'))/365,1)*12),1)*30)+1) days
from dual
DateTime values in T-SQL are stored as floats. You can just subtract the dates from each other and you now have a new date that is the timespan between them.
declare #birthdate datetime
set #birthdate = '6/15/1974'
--age in years - short version
print year(getdate() - #birthdate) - year(0)
--age in years - visualization
declare #mindate datetime
declare #span datetime
set #mindate = 0
set #span = getdate() - #birthdate
print #mindate
print #birthdate
print getdate()
print #span
--substract minyear from spanyear to get age in years
print year(#span) - year(#mindate)
print month(#span)
print day(#span)
CREATE FUNCTION DBO.GET_AGE
(
#DATE AS DATETIME
)
RETURNS VARCHAR(MAX)
AS
BEGIN
DECLARE #YEAR AS VARCHAR(50) = ''
DECLARE #MONTH AS VARCHAR(50) = ''
DECLARE #DAYS AS VARCHAR(50) = ''
DECLARE #RESULT AS VARCHAR(MAX) = ''
SET #YEAR = CONVERT(VARCHAR,(SELECT DATEDIFF(MONTH,CASE WHEN DAY(#DATE) > DAY(GETDATE()) THEN DATEADD(MONTH,1,#DATE) ELSE #DATE END,GETDATE()) / 12 ))
SET #MONTH = CONVERT(VARCHAR,(SELECT DATEDIFF(MONTH,CASE WHEN DAY(#DATE) > DAY(GETDATE()) THEN DATEADD(MONTH,1,#DATE) ELSE #DATE END,GETDATE()) % 12 ))
SET #DAYS = DATEDIFF(DD,DATEADD(MM,CONVERT(INT,CONVERT(INT,#YEAR)*12 + CONVERT(INT,#MONTH)),#DATE),GETDATE())
SET #RESULT = (RIGHT('00' + #YEAR, 2) + ' YEARS ' + RIGHT('00' + #MONTH, 2) + ' MONTHS ' + RIGHT('00' + #DAYS, 2) + ' DAYS')
RETURN #RESULT
END
SELECT DBO.GET_AGE('04/12/1986')
DECLARE #BirthDate datetime, #AgeInMonths int
SET #BirthDate = '10/5/1971'
SET #AgeInMonths -- Determine the age in "months old":
= DATEDIFF(MONTH, #BirthDate, GETDATE()) -- .Get the difference in months
- CASE WHEN DATEPART(DAY,GETDATE()) -- .If today was the 1st to 4th,
< DATEPART(DAY,#BirthDate) -- (or before the birth day of month)
THEN 1 ELSE 0 END -- ... don't count the month.
SELECT #AgeInMonths / 12 as AgeYrs -- Divide by 12 months to get the age in years
,#AgeInMonths % 12 as AgeXtraMonths -- Get the remainder of dividing by 12 months = extra months
,DATEDIFF(DAY -- For the extra days, find the difference between,
,DATEADD(MONTH, #AgeInMonths -- 1. Last Monthly Birthday
, #BirthDate) -- (if birthdays were celebrated monthly)
,GETDATE()) as AgeXtraDays -- 2. Today's date.
For the ones that want to create a calculated column in a table to store the age:
CASE WHEN DateOfBirth< DATEADD(YEAR, (DATEPART(YEAR, GETDATE()) - DATEPART(YEAR, DateOfBirth))*-1, GETDATE())
THEN DATEPART(YEAR, GETDATE()) - DATEPART(YEAR, DateOfBirth)
ELSE DATEPART(YEAR, GETDATE()) - DATEPART(YEAR, DateOfBirth) -1 END
There is an easy way, based on the hours between the two days BUT with the end date truncated.
SELECT CAST(DATEDIFF(hour,Birthdate,CAST(GETDATE() as Date))/8766.0 as INT) AS Age FROM <YourTable>
This one has proven to be extremely accurate and reliable. If it weren't for the inner CAST on the GETDATE() it might flip the birthday a few hours before midnight but, with the CAST, it is dead on with the age changing over at exactly midnight.
Here is how I calculate the age given a birth date and the current date.
select case
when cast(getdate() as date) = cast(dateadd(year, (datediff(year, '1996-09-09', getdate())), '1996-09-09') as date)
then dateDiff(yyyy,'1996-09-09',dateadd(year, 0, getdate()))
else dateDiff(yyyy,'1996-09-09',dateadd(year, -1, getdate()))
end as MemberAge
go
There is another method for calculate age is
See below table
FirstName LastName DOB
sai krishnan 1991-11-04
Harish S A 1998-10-11
For finding age,you can calculate through month
Select datediff(MONTH,DOB,getdate())/12 as dates from [Organization].[Employee]
Result will be
firstname dates
sai 27
Harish 20
I have created a function calculateAge that takes parameter dateOfBirth from outside and then it calculates the age in years, months and days and finally it returns in string format.
CREATE FUNCTION calculateAge(dateOfBirth datetime) RETURNS varchar(40)
BEGIN
set #currentdatetime = CURRENT_TIMESTAMP;
set #years = TIMESTAMPDIFF(YEAR,dateOfBirth,#currentdatetime);
set #months = TIMESTAMPDIFF(MONTH,dateOfBirth,#currentdatetime) - #years*12 ;
set #dayOfBirth = EXTRACT(DAY FROM dateOfBirth);
set #today = EXTRACT(DAY FROM #currentdatetime);
set #days = 0;
if (#today > #dayOfBirth) then
set #days = #today - #dayOfBirth;
else
set #decreaseMonth = DATE_SUB(#currentdatetime, INTERVAL 1 MONTH);
set #days = DATEDIFF(dateOfBirth, #decreaseMonth);
end if;
RETURN concat(concat( concat(#years , "years\n") , concat(#months , "months\n")), concat(#days , "days"));
END
Plenty of solutions have been given already, but I beleive this one to be both easy to understand and reliable, as it will handle leap years as well :
case when datepart(dayofyear, #birth) <= datepart(dayofyear, getdate())
then datepart(year, getdate()) - datepart(year, #birth)
else datepart(year, getdate()) - datepart(year, #birth) - 1
end
The idea is to simply compute the difference in years between the two years (birth and now), and substract 1 if the anniversary has not been reached for the current year.
declare #StartDate datetime = '2016-01-31'
declare #EndDate datetime = '2016-02-01'
SELECT #StartDate AS [StartDate]
,#EndDate AS [EndDate]
,DATEDIFF(Year,#StartDate,#EndDate) - CASE WHEN DATEADD(Year,DATEDIFF(Year,#StartDate,#EndDate), #StartDate) > #EndDate THEN 1 ELSE 0 END AS [Years]
,DATEDIFF(Month,(DATEADD(Year,DATEDIFF(Year,#StartDate,#EndDate) - CASE WHEN DATEADD(Year,DATEDIFF(Year,#StartDate,#EndDate), #StartDate) > #EndDate THEN 1 ELSE 0 END,#StartDate)),#EndDate) - CASE WHEN DATEADD(Month, DATEDIFF(Month,DATEADD(Year,DATEDIFF(Year,#StartDate,#EndDate) - CASE WHEN DATEADD(Year,DATEDIFF(Year,#StartDate,#EndDate), #StartDate) > #EndDate THEN 1 ELSE 0 END,#StartDate),#EndDate) , #StartDate) > #EndDate THEN 1 ELSE 0 END AS [Months]
,DATEDIFF(Day, DATEADD(Month,DATEDIFF(Month, (DATEADD(Year,DATEDIFF(Year,#StartDate,#EndDate) - CASE WHEN DATEADD(Year,DATEDIFF(Year,#StartDate,#EndDate), #StartDate) > #EndDate THEN 1 ELSE 0 END,#StartDate)),#EndDate) - CASE WHEN DATEADD(Month, DATEDIFF(Month,DATEADD(Year,DATEDIFF(Year,#StartDate,#EndDate) - CASE WHEN DATEADD(Year,DATEDIFF(Year,#StartDate,#EndDate), #StartDate) > #EndDate THEN 1 ELSE 0 END,#StartDate),#EndDate) , #StartDate) > #EndDate THEN 1 ELSE 0 END ,DATEADD(Year,DATEDIFF(Year,#StartDate,#EndDate) - CASE WHEN DATEADD(Year,DATEDIFF(Year,#StartDate,#EndDate), #StartDate) > #EndDate THEN 1 ELSE 0 END,#StartDate)) ,#EndDate) - CASE WHEN DATEADD(Day,DATEDIFF(Day, DATEADD(Month,DATEDIFF(Month, (DATEADD(Year,DATEDIFF(Year,#StartDate,#EndDate) - CASE WHEN DATEADD(Year,DATEDIFF(Year,#StartDate,#EndDate), #StartDate) > #EndDate THEN 1 ELSE 0 END,#StartDate)),#EndDate) - CASE WHEN DATEADD(Month, DATEDIFF(Month,DATEADD(Year,DATEDIFF(Year,#StartDate,#EndDate) - CASE WHEN DATEADD(Year,DATEDIFF(Year,#StartDate,#EndDate), #StartDate) > #EndDate THEN 1 ELSE 0 END,#StartDate),#EndDate) , #StartDate) > #EndDate THEN 1 ELSE 0 END ,DATEADD(Year,DATEDIFF(Year,#StartDate,#EndDate) - CASE WHEN DATEADD(Year,DATEDIFF(Year,#StartDate,#EndDate), #StartDate) > #EndDate THEN 1 ELSE 0 END,#StartDate)) ,#EndDate),DATEADD(Month,DATEDIFF(Month, (DATEADD(Year,DATEDIFF(Year,#StartDate,#EndDate) - CASE WHEN DATEADD(Year,DATEDIFF(Year,#StartDate,#EndDate), #StartDate) > #EndDate THEN 1 ELSE 0 END,#StartDate)),#EndDate) - CASE WHEN DATEADD(Month, DATEDIFF(Month,DATEADD(Year,DATEDIFF(Year,#StartDate,#EndDate) - CASE WHEN DATEADD(Year,DATEDIFF(Year,#StartDate,#EndDate), #StartDate) > #EndDate THEN 1 ELSE 0 END,#StartDate),#EndDate) , #StartDate) > #EndDate THEN 1 ELSE 0 END ,DATEADD(Year,DATEDIFF(Year,#StartDate,#EndDate) - CASE WHEN DATEADD(Year,DATEDIFF(Year,#StartDate,#EndDate), #StartDate) > #EndDate THEN 1 ELSE 0 END,#StartDate))) > #EndDate THEN 1 ELSE 0 END AS [Days]
select DOB as Birthdate,
YEAR(GETDATE()) as ThisYear,
YEAR(getdate()) - EAR(date1) as Age
from TableName
SELECT DOB AS Birthdate ,
YEAR(GETDATE()) AS ThisYear,
YEAR(getdate()) - YEAR(DOB) AS Age
FROM tableprincejain
DECLARE #DoB AS DATE = '1968-10-24'
DECLARE #cDate AS DATE = CAST('2000-10-23' AS DATE)
SELECT
--Get Year difference
DATEDIFF(YEAR,#DoB,#cDate) -
--Cases where year difference will be augmented
CASE
--If Date of Birth greater than date passed return 0
WHEN YEAR(#DoB) - YEAR(#cDate) >= 0 THEN DATEDIFF(YEAR,#DoB,#cDate)
--If date of birth month less than date passed subtract one year
WHEN MONTH(#DoB) - MONTH(#cDate) > 0 THEN 1
--If date of birth day less than date passed subtract one year
WHEN MONTH(#DoB) - MONTH(#cDate) = 0 AND DAY(#DoB) - DAY(#cDate) > 0 THEN 1
--All cases passed subtract zero
ELSE 0
END
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