In this post, we will learn how to calculate the time between two dates in year, month, and day format. There is a special function for getting a perfect year, month, and day count.

Normally, we use the DATEDIFF function of SQL for getting the years, months, and days between two dates but this function returns a perfect difference between the dates. Let's start creating this function.

Write the below code to create a function in the existing SQL database.

  1. CREATE FUNCTION Get_YearMonthDayCount_Custom
  2. (
  3. @FromDate DateTime
  4. ,@ToDate DateTime
  5. )
  6. RETURNS Varchar(100)
  7. AS
  8. BEGIN
  9. DECLARE @Year Int = 0, @Month Int = 0, @Day Int = 0, @Date DateTime, @ReturnValue Int = 0
  10. SET @Date = @FromDate
  11. --CALCULATE THE @YEAR
  12. IF(DATEPART(YEAR,@ToDate)>DATEPART(YEAR,@FromDate))
  13. BEGIN
  14. SET @Year = DATEDIFF(YEAR,@FromDate,@ToDate)
  15. SET @Date = DATEADD(YEAR,@Year,@FromDate) --UPDATE RUNNINGDATE
  16. IF(@Date>@ToDate)
  17. BEGIN
  18. SET @Year = DATEDIFF(YEAR,@FromDate,DATEADD(YEAR,-1,@ToDate)) --CALCULATE YEARS FROM @FROMDATE TO @TODATE - 1 YEAR
  19. SET @Date = DATEADD(YEAR,@Year,@FromDate) --UPDATE RUNNINGDATE
  20. END
  21. END
  22. --ADD 1 MONTH AS LONG AS RUNNING DATE IS SMALLER THAN OR EQUAL TO @TODATE
  23. WHILE @Date<=@ToDate
  24. BEGIN
  25. SET @Date = DATEADD(MONTH,1,@Date)
  26. IF (@Date<=@ToDate)
  27. BEGIN
  28. SET @Month=@Month+1
  29. END
  30. END
  31. --SET @DATE BACK 1 MONTH
  32. SET @Date=DATEADD(MONTH,-1,@Date)
  33. --START TO COUNT DAYS
  34. WHILE @Date<@ToDate
  35. BEGIN
  36. SET @Date=DATEADD(DAY,1,@Date)
  37. SET @Day=@Day+1
  38. END
  39. RETURN CONCAT(CONVERT(NVARCHAR(10),@Year),' Year ',CONVERT(NVARCHAR(10),@Month),' Month ',CONVERT(NVARCHAR(10),@Day),' Day')
  40. END
How to call the above function.
  1. DECLARE @FromDate DateTime, @ToDate DateTime
  2. SET @FromDate = '2018-09-01 17:52:01.467'
  3. SET @ToDate = '2018-10-19 17:52:01.467'
  4. SELECT dbo.Get_YearMonthDayCount_Custom(@FromDate,@ToDate)
Output
Output