Jeff's SQL Server Blog

Random Thoughts & Cartesian Products with Microsoft SQL Server
posts - 144, comments - 1810, trackbacks - 64

My Links

SQLTeam.com Links

News

Welcome to my weblog. My name is Jeff Smith, and I am a software developer in Boston, MA. Check in frequently for tips, tricks, commentary and ideas on SQL Server and .NET programming.


Subscribe





Archives

Post Categories

Programming

Sports

SQL

Essential SQL Server Date, Time and DateTime Functions

(2/13/07 Update: Once again, some great feedback has given us an even better Date() function -- and a Time() function as well.  Thank you Michael !)

(1/29/07 Update: Thank you to Fredrik for pointing out an issue with the Date() function when returning 3/1/2008 [see the comments] )

Part I: Standard Date and Time Functions

I've posted some variations of these before, but here they all are in 1 easy package:  The essential date and time functions that every SQL Server database should have to ensure that you can easily manipulate dates and times without the need for any formatting considerations at all.

They are simple, easy, and brief and you should use them any time you need to incorporate any date literals or date math in your T-SQL code.  I have always wondered why T-SQL omits these basic functions, but the beauty of user defined functions is that we can create them ourselves.

create  function DateOnly(@DateTime DateTime)
-- Returns @DateTime at midnight; i.e., it removes the time portion of a DateTime value.
returns datetime
as
    begin
    return dateadd(dd,0, datediff(dd,0,@DateTime))
    end
go

create function Date(@Year int, @Month int, @Day int)
-- returns a datetime value for the specified year, month and day
-- Thank you to Michael Valentine Jones for this formula (see comments).
returns datetime
as
    begin
    return dateadd(month,((@Year-1900)*12)+@Month-1,@Day-1)
    end
go

create function Time(@Hour int, @Minute int, @Second int)
-- Returns a datetime value for the specified time at the "base" date (1/1/1900)
-- Many thanks to MVJ for providing this formula (see comments).
returns datetime
as
    begin
    return dateadd(ss,(@Hour*3600)+(@Minute*60)+@Second,0)
    end
go

create function TimeOnly(@DateTime DateTime)
-- returns only the time portion of a DateTime, at the "base" date (1/1/1900)
returns datetime
as
    begin
    return @DateTime - dbo.DateOnly(@DateTime)
    end
go

create function DateTime(@Year int, @Month int, @Day int, @Hour int, @Minute int, @Second int)
-- returns a dateTime value for the date and time specified.
returns datetime
as
    begin
    return dbo.Date(@Year,@Month,@Day) + dbo.Time(@Hour, @Minute,@Second)
    end
go

Remember that you must prefix UDFs with the owner (usually dbo) when calling them.

Usage Examples:

  •  where TransactionDate >= dbo.Date(2005,1,2)  -- no formatting or implicit string conversions needed for date literals

  • select dbo.Date(year(getdate()), 1,1) -- returns the first day of the year for the current year.

  • select dbo.DateOnly(getdate()) -- returns only the date portion of the current day.

  • if dbo.TimeOnly(SomeDate) = dbo.Time(5,30,0)  -- check to see if the time for a given date is at 5:30 AM

  • select dbo.Date(year(getdate()), month(getdate()),1) -- returns the first day of the current month.

  • select dbo.Date(year(getdate()), month(getdate())+1,0) -- returns the last day of the current month.

  • where SomeDate >= dbo.DateOnly(getdate()) and SomeDate < dbo.DateOnly(getDate())+1 -- a simple way to get all transactions that occurred on the current date

  • select dbo.DateOnly(getdate()) + 1 + dbo.Time(14,30,0) -- returns tomorrow at 2:30 PM.
and so on ....

Part II:  Introducing TimeSpans to SQL Server

With those functions in place, we can add two more that will give us further flexibility when working with dates and times: The concept of a "TimeSpan", very similar to what is available in the .NET framework.

create function TimeSpan(@Days int, @Hours int, @Minutes int, @Seconds int)
-- returns a datetime the specified # of days/hours/minutes/seconds from the "base" date of 1/1/1900 (a "TimeSpan")
returns datetime
as
    begin
    return dbo.Time(@Hours,@Minutes,@Seconds) + @Days
    end

create function TimeSpanUnits(@Unit char(1), @TimeSpan datetime)
-- returns the # of units specified in the TimeSpan.
-- The Unit parameter can be: "d" = days, "h" = hours, "m" = minutes, "s" = seconds
returns int
as
    begin
    return case @Unit
        when 'd' then datediff(day, 0, @TimeSpan)
        when 'h' then datediff(hour, 0, @TimeSpan)
        when 'm' then datediff(minute, 0, @TimeSpan)
        when 's' then datediff(second, 0, @TimeSpan)
        else Null end
    end

Here, a TimeSpan is just a datetime offset from the "base" date of 1/1/1900.  Creating one is the same as creating a Time using the Time() function, but we have added a parameter for Days to give more flexibility.

The TimeSpanUnits() function works similar to standard T-SQL DatePart() function, but it returns the total # of units in the given time span.  So, if you create a time span of 1 day and 2 hours, then TimeSpanUnits("d") will return 1 and TimeSpanUnits("h") will return 26.  Negative values can be returned as well.  You also may wish to implement the TimeSpanUnits() function as multiple functions, one per unit (e.g., TimeSpanHours(), TimeSpanDays(), etc) depending on your preference.

Of course, a simple way to create a TimeSpan is to simply subtract two standard T-SQL DateTimes.  Also please note that we can add and subtract Dates, Times, and TimeSpans all together using standard + and - operators and everything will work as expected.  We can also add integers to our Dates and Times which will add entire days to the values.

Here's a TimeSpan usage example:

declare @Deadline datetime -- remember, we still use standard datetimes for everything, include TimeSpans
set @Deadline = dbo.TimeSpan(2,0,0,0)   -- the deadline is two days

declare @CreateDate datetime
declare @ResponseDate datetime

set @CreateDate = dbo.DateTime(2006,1,3,8,30,0)  -- Jan 3, 2006, 8:30 AM
set @ResponseDate = getdate() -- today

-- See if the response date is past the deadline:
select case when @ResponseDate > @CreateDate + @Deadline then 'overdue.' else 'on time.' end as Result

-- Find out how many total hours it took to respond:  

declare @TimeToRepond datetime
set @TimeToRespond = @ResponseDate - @CreateDate

select dbo.TimeSpanUnits('h', @TimeToRespond) as ResponseTotalHours

-- Return the response time as # of days, # of hours, # of minutes:
select dbo.TimeSpanUnits('d',@TimeToRespond) as Days, DatePart(hour, @TimeToRespond) as Hours, DatePart(minute, @TimeToRespond) as Minutes

-- Return two days and two hours from now:
select getdate() + dbo.TimeSpan(2,2,0,0)


Part III: Conclusion

We're not working with magic here, or creating new data types or concepts or incorporating the CLR into our database.  We are simply using the existing DateTime datatype to make our lives very easy and to implement efficient and simple date and time manipulation in T-SQL.

The fact that DateTimes are stored as standard numeric values and the fact that they can be added, subtracted and compared and that there is a standard "base" value (that evaluates to a numerical value of 0) means that we have all the power we need to do all kinds of things in T-SQL; we just need a few functions to help us out.

Final Note:  if you need the accuracy of milliseconds in your application, it is very easy to alter the above functions (or add new ones) that allow you to specify milliseconds in your times. 

see also:

Print | posted on Tuesday, January 02, 2007 11:38 AM

Feedback

# re: Essential SQL Server Date and Time Functions

The speed differences seem too small to measure, but here are my versions of some of those:
Create function [dbo].[DateOnly2](@DateTime DateTime)
-- Strips out the time portion of any dateTime value.
returns datetime
as
begin
return cast(cast(@DateTime as integer) as DateTime)
end

CREATE function [dbo].[TimeOnly2](@DateTime DateTime)
-- returns the only the time portion of a date, at the "base" date (1/1/1900)
returns datetime
as
begin
return cast(@DateTime - cast(@DateTime as Integer) as DateTime)
end

Plus one I didn't see you cover:

CREATE FUNCTION [dbo].[Epoch] ()
-- Returns beginning of time as DateTime
RETURNS DateTime
AS
BEGIN
RETURN cast(0 as DateTime)
END
1/3/2007 11:22 AM | James Curran

# re: Essential SQL Server Date and Time Functions

Hi James -- I used to do it the same way, but then someone pointed this out to me, and since then I've religiously used the DateAdd(DateDiff()) method:

declare @datetime datetime
set @datetime = '1/1/2006 11:59:59 PM'
select cast(cast(@DateTime as integer) as DateTime)

returns 1/2/2006 ...
1/3/2007 11:30 AM | Jeff

# re: Essential SQL Server Date and Time Functions

Same with the Time2 function, FYI:

declare @datetime datetime
set @datetime = '1/1/2006 11:59:29 PM'

select cast(@DateTime - cast(@DateTime as Integer) as DateTime)

returns the time on 12/31/1899.

1/3/2007 11:32 AM | Jeff

# re: Essential SQL Server Date and Time Functions

Yikkes! You're right! In fact, it fails for any PM time. It seems that CAST rounds to the nearest integer rather than truncating to the lower (as cast does most other places).

select cast(FLOOR(cast(@DateTime as float)) as datetime)

does work, but that's getting a bit too convoluted.
1/3/2007 1:08 PM | James Curran

# re: Essential SQL Server Date and Time Functions

Yeah, I had the same reaction when someone pointed that out to me, too. You also could subtract .5 from the DateTime before casting it, instead of using Floor(), but either way I prefer the method posted.
1/3/2007 3:27 PM | Jeff

# Essential SQL Server Date and Time Functions

1/3/2007 5:34 PM | Dontchaknow

# re: Essential SQL Server Date and Time Functions

Jeff, I've marked Bloglines to save this article. I HATE dealing with dates in SQL server. This will make life so much easier.

Of possible interest to you might be my latest blog post (just click my name, I linked right to the post). I wrote about how the aspnet_regsql (which I know isn't your team) creates stored procedures that don't work with SQL Server 2005 schemas and how to fix them. If you could pass that on to the correct team, I'd love it and I'm sure many would appreciate it.

And yes, I know there's a new way to do SQL cache dependencies in 2005, but the .Net 2.0 tool should at least support doing schemas on 2005. I've updated the Microsoft SP to support that. Please let me know what you think and if you'll be able to coherently explain that problem to the appropriate team.

Keep up the great work blogging. I wish you wrote more often.
1/3/2007 8:36 PM | Chris Benard

# re: Essential SQL Server Date and Time Functions

More interesting SQL DATE stuff (in just T-SQL) here:

http://musingmarc.blogspot.com/2006/07/more-on-dates-and-sql.html
1/4/2007 2:34 AM | Marc Brooks

# re: Essential SQL Server Date and Time Functions

The function Date(@Year int, @Month int, @Day int) has a bug.

select dbo.Date(2008,3,1) -> 2008-02-29 00:00:00.000

dateadd(day, @Day-1, dateadd(month, @Month-1, dateadd(year, (@Year-1900),0)))

works better

1/9/2007 9:44 AM | Fredrik Stax"ang

# re: Essential SQL Server Date, Time and DateTime Functions

In function Date you can shorten the formula from this:
dateadd(day, @Day-1, dateadd(month, @Month-1, dateadd(year, (@Year-1900),0)))
to this:
dateadd(month,((@Year-1900)*12)+@Month-1,@Day-1)

Test results that I posted on the link below indicate that it is also faster, probably because there is only one call to to the dateadd function.
http://www.sqlteam.com/forums/topic.asp?TOPIC_ID=66471



In function Time you can shorten the formula from this:
dateadd(hour, @Hour, 0) + dateadd(minute, @Minute,0) + dateAdd(second, @Second,0)
to this:
dateadd(ss,(@Hour*3600)+(@Minute*60)+@Second,0)


2/4/2007 3:15 AM | Michael Valentine Jones

# re: Essential SQL Server Date, Time and DateTime Functions

Michael -- I like it! Anything short and simple and fast is good for me. If you don't mind, I will update the functions with your suggested versions.
2/5/2007 10:29 AM | Jeff

# re: Essential SQL Server Date, Time and DateTime Functions

Fine with me.
2/5/2007 4:16 PM | Michael Valentine Jones

# re: Essential SQL Server Date, Time and DateTime Functions

Fantasitc.
2/14/2007 9:44 AM | Nate Suda

# re: Essential SQL Server Date, Time and DateTime Functions

I hate to be a pest after you modified the Date function code already, but Peter Larsson discovered that changing the formula from this:
dateadd(month,((@Year-1900)*12)+@Month-1,@Day-1)
to this:
dateadd(month,(12*@Year)-22801+@Month,@Day-1)
resulted in about a 3% to 5% reduction in runtime with inline code, and the code is slightly shorter.

You can see the discussion on this thread:
http://www.sqlteam.com/forums/topic.asp?TOPIC_ID=22339


2/15/2007 8:18 PM | Michael Valentine Jones

# re: Essential SQL Server Date, Time and DateTime Functions

When trying to create the functions under User Defined Functions I get an error stating that they already exist.

What im I doing wrong?

Thanks for the great functions. I wish i could make them work.
2/21/2007 2:09 PM | Rob

# re: Essential SQL Server Date, Time and DateTime Functions

Rob: Functions exist in your database with the same name -- either you'vfe run the script twice or someone else has created existing functions with the same name. If this is a production system Don't Touch It until you know what's going on (ask your local DBA).

Otherwise change "Create Function" to "Alter function".
3/8/2007 6:42 PM | steveg

# re: Essential SQL Server Date, Time and DateTime Functions

Can anyone give me any suggestions with regards to calculating minutes between two events (@OriginalSentEmailTime and @FirstResponseEmailTime) where any time after 5pm or before 9am do not get counted in the total number of minutes? As well Saturdays and Sundays should not count towards the total number of minutes. Everything I have tried gets pretty ugly.
3/21/2007 6:09 PM | Johnh

# re: Essential SQL Server Date, Time and DateTime Functions

Jeff,

Your datetime functions have helped me a lot while writing triggers in SQL SERVER. Thanx for your article.
3/28/2007 5:07 AM | suresh

# re: Essential SQL Server Date, Time and DateTime Functions

thanks for the handy functions jeff! i've been convert(smalldatetime, convert(Varchar(10), @mydatetime, 101)) way too long and should have remembered to use a func!
3/29/2007 12:10 AM | Arjun

# re: Essential SQL Server Date, Time and DateTime Functions

Yep, this page goes right to the Favorites menu... Thanks!
4/20/2007 5:11 AM | Joris

# re: Essential SQL Server Date, Time and DateTime Functions

Hi
I want only times to be added
wat i mean is i have two fields ontime(varchar) and duration(smallint )
where ontime holds 9:50 as data and duration holds 45 as data
now i need to add these two .

Can any one tell how it can be possible
4/25/2007 2:55 AM | prasad

# re: Essential SQL Server Date, Time and DateTime Functions

prasad -- did you even read the article at all?

First, Do not use SmallInt and/or VARCHAR to store dates or times!!!!! Use proper datatypes. That would be DateTime.

Once you have done that, and both of those columns are DateTimes, then you simply ... add them together!!!

select onTime, Duration, onTime + Duration
from YourTable

That's it! See how using correct datatypes makes things easy ???
4/25/2007 8:50 AM | Jeff

# re: Essential SQL Server Date, Time and DateTime Functions

its really good stuff. thanks
5/9/2007 6:17 PM | hey

# re: Essential SQL Server Date, Time and DateTime Functions

Hi,

These date information is very useful. Thank you. I'm however struggling to subtract one date from another to get number of days as result. For example
select.........,
case when calc_del_date > act_del_date then (calc_del_date - act_del_date)
when calc_del_date < act_del_date then (act_del_date - calc_del_date)
else ''
end as days_early_late

Can you help???
6/5/2007 11:14 AM | katerina

# re: Essential SQL Server Date, Time and DateTime Functions

katerina -- I show exactly how to do this in the article -- did you read the part about TimeSpans and see the examples?
6/5/2007 11:18 AM | Jeff

# re: Essential SQL Server Date, Time and DateTime Functions

Hi,
I have to use SQL server 2005 as the backend db for reporting using cognos. One of my reports needs the minutes between 2 dates. Can you tell me the best way of doing it? do i create a function in the db or create a dynamic variable in reportnet. If i have to create a function , pls let me know how to create it?
6/6/2007 1:42 AM | sandeep

# re: Essential SQL Server Date, Time and DateTime Functions

sandeep:

> If i have to create a function , pls let me know how to create it?

There is a great article for this -- see this article: http://weblogs.sqlteam.com/jeffs/archive/2007/01/02/56079.aspx

:)
6/11/2007 3:10 PM | Perry

# re: Essential SQL Server Date, Time and DateTime Functions

Can someone suggest a way to get the midnight of the first day of current month ?
6/19/2007 3:36 PM | Neerav

# re: Essential SQL Server Date, Time and DateTime Functions

>> Can someone suggest a way to get the midnight of the first day of current month ?

The article explains with an example exactly how to do that.
6/19/2007 3:55 PM | Jeff

# re: Essential SQL Server Date, Time and DateTime Functions

What if you need to store dates older than 1753. I am working on a project dealing with historical data and this is a requirement.
6/19/2007 11:15 PM | Mark M

# re: Essential SQL Server Date, Time and DateTime Functions

Hi, Thanks very much for this, I was having a lot of trouble with a GROUP BY DateTime statement, where the records had been inserted milliseconds apart ... the DateOnly is just what I was after for GROUP BY'ing dates with differences of seconds between records.
8/3/2007 12:54 AM | Jarrod N

# re: Essential SQL Server Date, Time and DateTime Functions

thanks
8/15/2007 4:23 AM | ww

# Is there any function like LastDate and FirstDate of Oracle

I am havig a problem at the time of working with date. I want function Last Date and First Date.
8/16/2007 2:30 AM | Sanjay Kumar Dinda

# re: Essential SQL Server Date, Time and DateTime Functions

These Date & Time functions helped me out in delivering my code on Date & Time

Many Thanks!!
8/17/2007 3:47 AM | Jim

# re: Essential SQL Server Date, Time and DateTime Functions

Good Information

DotNetGuts
http://dotnetguts.blogspot.com
8/19/2007 1:43 AM | dotnetguts

# re: Essential SQL Server Date, Time and DateTime Functions

declare @datetime datetime
set @datetime = '1/1/2006 12:59:00 '
select cast(convert(varchar(10),@DateTime,101 ) as datetime)

9/13/2007 1:46 AM | santosh

# re: Essential SQL Server Date, Time and DateTime Functions

i would like to know how to get the data in employee table who are hired in the month of janauray irrespective of the year in which they are hired
9/22/2007 1:12 AM | swati

# re: Essential SQL Server Date, Time and DateTime Functions

I am also screwed up with the date time format .. first time using this on MSSQL for writting TSQL stored procedures....

Its a pure rubbish...

Arun
9/27/2007 5:17 AM | arun

# re: Essential SQL Server Date, Time and DateTime Functions

The date and time format is an headache. It has become pain in my neck.

Shishir Gupta

IT Head
http://www.naukrisalah.com
9/27/2007 6:31 AM | Shishir Gupta

# re: Essential SQL Server Date, Time and DateTime Functions

Hi, i want to know how do i fire a trigger at 2359 daily and i can transfer my current data into archive.
10/1/2007 11:46 PM | Vincent

# re: Essential SQL Server Date, Time and DateTime Functions

Thank you sooooo much. Your efforts here have saved me a lot of time. Thanks for everyone's input and keep up the good work!!
10/1/2007 11:56 PM | dev lead

# re: Essential SQL Server Date, Time and DateTime Functions

Hi Sir,

I have a specified date like(22/01/2010) and i want a date of the day(like: sunday or monday) just before 22/01/22. so is there any function like this please help.

thanks :
Saurabh
10/23/2007 3:05 AM | saurabh

# re: Essential SQL Server Date, Time and DateTime Functions

Hello. If it is not inappropriate for me to state here, I have a small project that addresses some of these DateTime issues, including TimeSpan output. The project is called SQL# (http://www.SQLsharp.com/) and is a .Net CLR based library of Stored Procedures and User-Defined Functions to address functionality not inherently in T-SQL. Currently, the DateTime related functions are:

BusinessDays
DaysInMonth
DaysLeftInYear
FormatTimeSpan
FirstDayOfMonth
FullDateString
FullTimeString
IsBusinessDay
IsLeapYear
LastDayOfMonth

The "FormatTimeSpan" function allows you to pass in two DATETIME fields and a text format string that will then output the timespan in the format you specified as an NVARCHAR.

The manual has full examples of all of these.
10/24/2007 11:16 AM | Solomon Rutzky

# re: Essential SQL Server Date, Time and DateTime Functions

Hello Jeff/other techies,
I have a nice problem before you, I need to find out the peak users logged in to the system

suppose 9:23 to 10:23 there are 800 users logged in
9:40 to 10:40 there are 900 users logged in,
11:33 to 12:33 there are 978 users logged in

In Short I want to group by <date conditionhere> having count(*) >900 (peak users)

select convert(varchar,min(logged_in),105),COUNT(*)
from tbl_UM_login r
where
convert(varchar,logged_in,105) < convert(varchar, getDate(), 105)
AND convert(varchar,logged_in,105) > convert(varchar, dateadd(dd,-7,getDate()), 105)
GROUP BY DATEDIFF(dd,getDate(),logged_in)
HAVING COUNT(*) > @peakUsers
10/29/2007 1:01 PM | Subbu

# Mr.

Question: I have a dates in this format: 10/11/2007 6:33:45 PM

However I need to run a sql query to group by date (without the time) eg

SELECT TOP (100) PERCENT OrderDate, SUM(OrderTotal) AS DateTotal
FROM dbo.tbl_Order
GROUP BY OrderDate
ORDER BY OrderDate

How do I do this?
Right now it groups the dates and time. thanks for any tips.
11/10/2007 4:27 AM | Aron

# I need All months name in SQL with songle query

Please I need result

jan
feb
mar
apr
may like this


Thank You
11/14/2007 1:01 PM | Shabeer M

# re: Essential SQL Server Date, Time and DateTime Functions

Hello all -
I am pretty new to this and similarly new to MS Sql so please bear with me. I have been following this thresd and others and am trying to find a solution to a similar problem.

I have two dates in a table, a received date and a resolved date. I am tasked with reporting on the time interval between the received date and the resolved date. the results should be in minutes. Any help will be appreciated.

Here is what I have but non of these appear to be acurate. What am I doing wrong or what is the best approach

select
im_issue_no,
im_received_date,
avg(cast(im_resolved_date as integer) - cast(im_Received_date as integer)) as AVG,
avg((CONVERT (FLOAT, DATEPART(hh, im_resolved_date) * 60 + DATEPART(n, im_resolved_date)) / 60) - (CONVERT (FLOAT, DATEPART(hh, im_Received_date) * 60 + DATEPART(n, im_Received_date)) / 60)) as AVG_2,
datediff(minute, im_received_date, im_resolved_date) as Minutes,
datediff(Hour, im_received_date, im_resolved_date)as Hours,
im_resolved_date
from
issues
where
im_issue_no = 24482
group by
im_issue_no,im_received_date,im_resolved_date
11/15/2007 4:35 PM | Fred

# re: Essential SQL Server Date, Time and DateTime Functions

Fred -- Without sample data, expected results, or more specifics, I have no idea what specifically you are looking for. The worst thing to do when asking for help is to present code that doesn't work and then ask for someone to fix it without providing clear, precise specifications and sample input and expected output. I recommend visiting the SQLTeam forums for more help, and be a lot more detailed there and you'll get the help you need.

Also, this article may be helpful to you:

http://www.sqlteam.com/article/working-with-time-spans-and-durations-in-sql-server
11/15/2007 4:39 PM | Jeff

# re: Essential SQL Server Date, Time and DateTime Functions

i have 2 datetime columns startdatetime and enddatetime and some event varchar column.
now my question is how to insert into these columns datetime in format or style i want to use while convert and insert..

something of this type.. but this is not working

insert into mydatetimeEvents
select convert(commencedatetime, 'Jan 01 2007 09:00AM',100),
convert(enddatetime, 'Jan 01 2007 09:00PM',100),'Anniversaries')

mydatetimeEvents-tablename
commencedatetime,enddatetime-column name-datatype-datetime
style-100
aniversaries-some other column of dattype varchar
11/16/2007 5:43 AM | Prasanna

# re: Essential SQL Server Date, Time and DateTime Functions

Prasanna -- you should really consider checking Books Online or reading any other SQL Server resource (books, google, MSDN) to find out how Convert() works and what it expects for arguments. And you should ask questions like this in programming forums, such as SQLTeam, not in blog comments.
11/16/2007 10:46 AM | Jeff

# re: Essential SQL Server Date, Time and DateTime Functions

How to get only date with format dd/MM/yyyy.......?

My client want all date with format like that. I already user DateOnly like below:

BEGIN function [dbo].[DateOnly](@DateTime DateTime)
-- Returns @DateTime at midnight; i.e., it removes the time portion of a DateTime value.
returns datetime
as
begin
return dateadd(dd,0, datediff(dd,0,@DateTime))
end

but it return with datetime like this '2006-04-17 00:00:00.000'
12/4/2007 4:29 AM | sally

# re: Essential SQL Server Date, Time and DateTime Functions

Sally that is a formatting question, it has nothing to do with T-SQL. Format your data at your presentation layer, never at your database layer.

see: http://weblogs.sqlteam.com/jeffs/archive/2007/08/29/SQL-Dates-and-Times.aspx
12/4/2007 4:42 PM | Jeff Smith

# re: Essential SQL Server Date, Time and DateTime Functions

Sally, For display purposed only, you could do this...

function [dbo].[DisplayDate](@DateTime DateTime)
returns varchar(10)
as
begin
return cast(month(@DateTime) as varchar) + '/' +
cast(day(@DateTime) as varchar) + '/' +
cast(year(@DateTime) as varchar)
end
12/26/2007 3:44 PM | Dean

# re: Essential SQL Server Date, Time and DateTime Functions

Dean -- great example of why you should not try to format in T-SQL. It no longer returns a date that can be compared, sorted, or used in any date functions; it doesn't actually follow the format specification she asked for, and it is longer, more complicated and less efficient than simply returning the date value and letting the client format it.

Why is this so hard to people to grasp? Why do people insist on making simple things more complicated?
12/26/2007 5:01 PM | Jeff

Post Comment

Title  
Name  
Email
Url
Comment   
Please add 6 and 4 and type the answer here:

Powered by: