Monday, August 03, 2009 12:43 PM
Hello all, I wanted to write some filters on a query I had and I needed to compare some datetime variables, but only the time part of the datetime and not the full datetime value. I realized there is no built in function in MS Sql Server to isolate or separate the time field out of a datetime value or the date field out of a datetime value. I googled some solutions on the internet and non of them gave me the quick simple solution I needed so I decided to approach the problem with a simple solution. I wrote two functions called GetTimeOnly and GetDateOnly and they serve a simple purpose, to isolate the time or date out of a datetime value.
Here is the sql code for them.
create function GetTimeOnly(@val datetime)
returns datetime
begin
IF (@val is null)
return null
return cast(
cast(datepart(hh,@val) as varchar(2)) + ':' +
cast(datepart(mi,@val) as varchar(2)) + ':' +
cast(datepart(ss,@val) as varchar(2)) + '.' +
cast(datepart(ms,@val) as varchar(4))
as datetime)
end
create function GetDateOnly(@val datetime)
returns datetime
begin
if (@val is null)
return null
return cast(
cast(datepart(yyyy,@val) as varchar(4)) + '-' +
cast(datepart(mm,@val) as varchar(2)) + '-' +
cast(datepart(dd,@val) as varchar(2))
as datetime)
end
go
Its usage is simple and straight forward, instead of using the datetime variable directly in an sql query, just put it in the function that you need, for example:
select dbo.GetTimeOnly(getdate()) as TimeOnly, dbo.GetDateOnly(getdate()) as DateOnly
Now using functions like DateDiff or comparing with
“>” and
“<” becomes very easy.