Find elapsed time between two datetime values

Say you want to find how much time has passed since 11:34 AM this morning. You can do it like this:

DECLARE @date DATETIME = '20130711 11:34:00.000';
SELECT CAST(GETDATE()-@date AS TIME);

Awesome, isn’t it? Honestly, did you know that you can just add and subtract datetime values just like that!!

Oh wait! What did you say? That you can’t ADD two datetime values? Well, bud! What about this?

DECLARE @date DATETIME = '20130711 11:34:00.000';
DECLARE @tmp DATETIME = CAST(GETDATE()-@date AS TIME);

SELECT @date + @tmp;
-- gives 2013-07-11 17:42:24.823


If you are saying to yourself “pffffft! what is the big deal!!”, you are missing the point! This blog is supposed to be shallow. It contains ONLY things that you can find in another 11,757 blogs. But it helps me get my name out there and promote myself as a SQL expert. So there!!

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