Get Difference in Days, Hours, Minutes and Seconds Between Two Dates in Sql Server.

Introduction: In this article I am going to share how to calculate exact day, hour, minute and second difference between two specific dates.

Description: While working on project I got the requirement to show user his last login time on his dashboard whenever he/she log in to website. Format required was as shown in image. There may be many other cases when similar option is required. So I have shared this so that it might be helpful to others if required.

Implementation: Let’s take an example to get what we need.

If you simply want the difference between last login and current date in days, hours, minutes and seconds separately then below query will help you.

DECLARE @LoginDate DATETIME='2016-09-10 14:45:55', @CurrentDate DATETIME=GETDATE();

SELECT @CurrentDate AS CurrentDate,@LoginDate AS LastLoginDate ,
DATEDIFF(SECOND, @LoginDate, @CurrentDate) / 60 / 60 / 24 AS TotalDays,
DATEDIFF(SECOND, @LoginDate, @CurrentDate) / 60 / 60 % 24 AS TotalHours,
DATEDIFF(SECOND, @LoginDate, @CurrentDate) / 60 % 60 AS TotalMinutes,
DATEDIFF(SECOND, @LoginDate, @CurrentDate) % 60 AS TotalSeconds

Output will be: 
CurrentDate
LastLoginDate
TotalDays
TotalHours
TotalMinutes
TotalSeconds
2016-10-10 22:01:14.123
2016-09-10 14:45:55.000
30
7
15
19


To get the difference between last login and current date in the format as shown below output.

DECLARE @LoginDate DATETIME='2016-09-10 14:45:55', @CurrentDate DATETIME=GETDATE();

SELECT @CurrentDate AS CurrentDate, CAST(DATEDIFF(SECOND, @LoginDate, @CurrentDate) / 60 / 60 / 24 AS NVARCHAR(30)) + ' days, '
+ CAST(DATEDIFF(SECOND, @LoginDate, @CurrentDate) / 60 / 60 % 24 AS NVARCHAR(30)) + ' hours, '
+ CAST(DATEDIFF(SECOND, @LoginDate, @CurrentDate) / 60 % 60 AS NVARCHAR(30)) + ' minutes and '
+ CAST(DATEDIFF(SECOND, @LoginDate, @CurrentDate) % 60 AS NVARCHAR(30)) + ' seconds ago.' AS LastLogin

Output will be:
CurrentDate
LastLogin
2016-10-10 22:01:14.123
30 days, 7 hours, 15 minutes and 19 seconds ago.

Now over to you:
A blog is nothing without reader's feedback and comments. So please provide your valuable feedback so that i can make this blog better and If you like my work; you can appreciate by leaving your comments, hitting Facebook like button, following on Google+, Twitter, Linkedin and Pinterest, stumbling my posts on stumble upon and subscribing for receiving free updates directly to your inbox . Stay tuned and stay connected for more technical updates. 
Previous
Next Post »

If you have any question about any post, Feel free to ask.You can simply drop a comment below post or contact via Contact Us form. Your feedback and suggestions will be highly appreciated. Also try to leave comments from your account not from the anonymous account so that i can respond to you easily..