Tip of the Day: A DateOnly function in SQL Server

It occurs to me that I’ve probably written several versions of this function in various installations on SQL Sever over the last 10+ years (10 years 2 months, 26 days – to be exact) since I started using SQL Server. I should really put it somewhere that I can refer to it easily and not have to re-write it again. (So why not put it in my blog?)

It’s a simple little thing that takes a DATETIME and returns the same but without the time elements, basically, it returns the date only.

CREATE FUNCTION [dbo].[DateOnly]
(
  @DateTime DATETIME
)
RETURNS DATETIME
AS
BEGIN
  RETURN 
    DATEADD(MILLISECOND, -DATEPART(MILLISECOND, @DateTime),
      DATEADD(SECOND, -DATEPART(SECOND, @DateTime),
        DATEADD(MINUTE, -DATEPART(MINUTE, @DateTime), 
          DATEADD(HOUR, -DATEPART(HOUR, @DateTime), @DateTime))));
END

1 Comment

  1. Jim Danby says:

    You can also use CONVERT(DATE, )

Leave a Comment

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 )

Connecting to %s