473,396 Members | 1,797 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes and contribute your articles to a community of 473,396 developers and data experts.

Essential SQL Server Date, Time and DateTime Functions

yasirmturk
Standard Date and Time Functions

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.

Expand|Select|Wrap|Line Numbers
  1. create  function DateOnly(@DateTime DateTime)
  2. -- Returns @DateTime at midnight; i.e., it removes the time portion of a DateTime value.
  3. returns datetime
  4. as
  5.     begin
  6.     return dateadd(dd,0, datediff(dd,0,@DateTime))
  7.     end
  8. go
  9.  
  10. create function Date(@Year int, @Month int, @Day int)
  11. -- returns a datetime value for the specified year, month and day
  12. -- Thank you to Michael Valentine Jones for this formula (see comments).
  13. returns datetime
  14. as
  15.     begin
  16.     return dateadd(month,((@Year-1900)*12)+@Month-1,@Day-1)
  17.     end
  18. go
  19.  
  20. create function Time(@Hour int, @Minute int, @Second int)
  21. -- Returns a datetime value for the specified time at the "base" date (1/1/1900)
  22. -- Many thanks to MVJ for providing this formula (see comments).
  23. returns datetime
  24. as
  25.     begin
  26.     return dateadd(ss,(@Hour*3600)+(@Minute*60)+@Second,0)
  27.     end
  28. go
  29.  
  30. create function TimeOnly(@DateTime DateTime)
  31. -- returns only the time portion of a DateTime, at the "base" date (1/1/1900)
  32. returns datetime
  33. as
  34.     begin
  35.     return @DateTime - dbo.DateOnly(@DateTime)
  36.     end
  37. go
  38.  
  39. create function DateTime(@Year int, @Month int, @Day int, @Hour int, @Minute int, @Second int)
  40. -- returns a dateTime value for the date and time specified.
  41. returns datetime
  42. as
  43.     begin
  44.     return dbo.Date(@Year,@Month,@Day) + dbo.Time(@Hour, @Minute,@Second)
  45.     end
  46. go
Remember that you must prefix UDFs with the owner (usually dbo) when calling them.

Usage Examples:

Expand|Select|Wrap|Line Numbers
  1.    *  where TransactionDate >= dbo.Date(2005,1,2)  -- no formatting or implicit string conversions needed for date literals
  2.  
  3.     * select dbo.Date(year(getdate()), 1,1) -- returns the first day of the year for the current year.
  4.  
  5.     * select dbo.DateOnly(getdate()) -- returns only the date portion of the current day.
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.

Expand|Select|Wrap|Line Numbers
  1. create function TimeSpan(@Days int, @Hours int, @Minutes int, @Seconds int)
  2. -- returns a datetime the specified # of days/hours/minutes/seconds from the "base" date of 1/1/1900 (a "TimeSpan")
  3. returns datetime
  4. as
  5.     begin
  6.     return dbo.Time(@Hours,@Minutes,@Seconds) + @Days
  7.     end
  8.  
  9. create function TimeSpanUnits(@Unit char(1), @TimeSpan datetime)
  10. -- returns the # of units specified in the TimeSpan.
  11. -- The Unit parameter can be: "d" = days, "h" = hours, "m" = minutes, "s" = seconds
  12. returns int
  13. as
  14.     begin
  15.     return case @Unit
  16.         when 'd' then datediff(day, 0, @TimeSpan)
  17.         when 'h' then datediff(hour, 0, @TimeSpan)
  18.         when 'm' then datediff(minute, 0, @TimeSpan)
  19.         when 's' then datediff(second, 0, @TimeSpan)
  20.         else Null end
  21.     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:

Expand|Select|Wrap|Line Numbers
  1. declare @Deadline datetime -- remember, we still use standard datetimes for everything, include TimeSpans
  2. set @Deadline = dbo.TimeSpan(2,0,0,0)   -- the deadline is two days
  3.  
  4. declare @CreateDate datetime
  5. declare @ResponseDate datetime
  6.  
  7. set @CreateDate = dbo.DateTime(2006,1,3,8,30,0)  -- Jan 3, 2006, 8:30 AM
  8. set @ResponseDate = getdate() -- today
  9.  
  10. -- See if the response date is past the deadline:
  11. select case when @ResponseDate > @CreateDate + @Deadline then 'overdue.' else 'on time.' end as Result
  12.  
  13. -- Find out how many total hours it took to respond:  
  14. declare @TimeToRepond datetime
  15. set @TimeToRespond = @ResponseDate - @CreateDate
  16.  
  17. select dbo.TimeSpanUnits('h', @TimeToRespond) as ResponseTotalHours
  18.  
  19. -- Return the response time as # of days, # of hours, # of minutes:
  20. select dbo.TimeSpanUnits('d',@TimeToRespond) as Days, DatePart(hour, @TimeToRespond) as Hours, DatePart(minute, @TimeToRespond) as Minutes
  21.  
  22. -- Return two days and two hours from now:
  23. select getdate() + dbo.TimeSpan(2,2,0,0)
Aug 15 '08 #1
0 16469

Sign in to post your reply or Sign up for a free account.

Similar topics

8
by: Gerrit Holl | last post by:
Posted with permission from the author. I have some comments on this PEP, see the (coming) followup to this message. PEP: 321 Title: Date/Time Parsing and Formatting Version: $Revision: 1.3 $...
7
by: Harag | last post by:
Hi all I think this is in the wrong group but since I don't read others much or code in java script I was wondering if anyone could help me with this small problem, as I code mostly in ASP...
1
by: simina | last post by:
Hi... I have an "appointments" page where the user should (or not necessarily) choose a date and time for his appointment, from 6 combo boxes:year, month, day, hour, minute and AM or PM, without...
7
by: Don | last post by:
Hi all, With regards to the following, how do I append the datetimestamp to the filenames in the form? The files are processed using the PHP script that follows below. Thanks in advance,...
0
by: Chris | last post by:
Can someone point me the right way? I'm trying to use the date/time extensions but with little luck. Here's what I've got: <?xml version="1.0" encoding="UTF-8"?> <xsl:stylesheet version="1.0"...
1
by: seash | last post by:
H when i execute this query, my query is crashing throwing an exception "cant convert char datatype to datetime type format my query is "insert into mytable(mydate) values ('"+ varmydate+ "')...
3
by: RSB | last post by:
Hi Every one , IS there any Date Time Control with .Net. All i want to read is the Date and Time in a Single Field like 12/31/2004 09:23:23AM. if there is any then any examples for it. and if not...
10
by: okaminer | last post by:
Hi I have a program which need to get the date in the format of dd/MM/yyyy (example 24/7/2005) but when I use DateTime.Now().ToShortDatetime() the date come back as MM/dd/yyyy (example...
7
by: Jerome | last post by:
Hallo, I know a lot has already been told about date/time fields in a database but still confuses me, specif when dealing with SQLserver(Express). It seems that sqlserver only accepts the date in...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.