Robyn Page’s SQL Server DATE/TIME Workbench

To celebrate the seventh anniversary of Robyn Page's classic workbench, Phil brings it right up to date. What starts as a gentle introduction to the use of dates in SQL Server ends up with some unusual tricks in creating calendars and calculating Mardi Gras.

  • revised: 21th Aug 2013 by Phil Factor
  • revised: 20th Sep 2012 by Phil Factor
  • revised: 11th May 2010 by Phil Factor

Using dates, and times in SQL Server: a workbench approach

I’d like to encourage you to experiment. One never fails to come up with surprises; for example, I’d never, before writing this, considered using LIKE when searching Date fields, or using the { t '2:40'} in a stored procedure as a literal date. Likewise, I always like to see as many examples as possible in any articles on SQL Server. There is nothing like it for getting ideas going. Formal descriptions are fine for those with strange extra lumps in their brains, but I’d prefer to see clear explanations peppered with examples! If I have any general advice, it is to use the strengths of the DATETIME, DATE, DATETIME2 and DATETIMEOFFSET data types and never attempt to bypass their use, by storing dates or times in any other formats such as varchars or integers. I’ve never come across a circumstance where such a practice has provided any lasting benefit. Also, keep clearly in mind the differences between the presentation format, data-interchange formats and storage formats of dates and times. Remember also the difference between an interval of time and a date.

Contents

The Principles

Basically, there are three different ways of representing dates, and the same principles apply to other quantities to do with humanity, such as money. Dates can be represented in a human-readable form, the ‘presentation’ mode, they can be represented in their storage form, or in their data-interchange form.

We can show this easily:

These have entirely different purposes, and it helps to understand the distinction. The storage form is what is kept in the data pages, and what is stored and searched on. Each databases system uses a different format and SQL Server has several! The presentation form is what is presented to us to understand as unambiguously and quickly as possible. The data-interchange form is used to transmit a date and time between systems, languages and time-zones.

The DataTypes

The date and time DataTypes on SQL Server 2008 and 2012 – time, date, smalldatetime, datetime, datetime2 and datetimeoffset – are greatly superior to those of previous versions of SQL Server. Why? Most importantly, we now get a standard means of recording a moment in time that takes into account ‘Local time’. Were the world flat, and the sun going around it, the DateTime format would be ideal. If you need to collect, compare, and aggregate from different locations in different time-zones, then Dates and Times must be recorded in terms of the local time, together with the offset from Coordinated Universal Time (UTC) to local time. For this, the DATETIMEOFFSET data type is ideal, and it works much like DateTime.

These date and time functions illustrate what I mean but they won’t show you the storage form, just the presentation or data-interchange form.

Why 1753 for the DATETIME range? That’s when the Gregorian calendar was generally adopted. Any dates before then have a certain ambiguity. The ‘Accuracy’ of these times is nothing like the precision of the datatype, which is designed for externally-sourced scientific data. The ‘granularity’ of the times you get from the GetDate functions is around 15 Ms, but around 1 Ms for the SYS versions of the functions.

As a general rule, use datetimeoffset where you can, use Time and Date where the data really is either just a time or just a date, but where you can get away with just using ‘local time’ (rare). I can’t think of a reason for using smalldatetime, and unless you are stuck on SQL Server 2000 or 2005, you’re very unlikely to need DateTime any more. The DateTimeOffset can take ten bytes of storage, but DateTimeOffst(2) reduces this to 7, and gives you plenty of precision for commercial applications. If you have a reason to be repelled by DateTimeOffset, then use DATETIME2, which has increased precision, and the full range of dates back to 1 AD.

All these different datatypes work the same way with the date functions. all these functions, for example, pass back different ‘storage’ datatypes, but give the same ‘presentation type’ date and time as a string in the ‘European default’ format (113).

Inputting dates

A user will supply dates in a number of formats and, at some point, you will need to get it into one of the Date/Time DataTypes in the database.

SQL Server 2012 adds a whole lot of functions to convert from parts of a date (e.g. year, month, day, hour, minute, seconds, milliseconds) to a SQL Server date. These are merely conveniences since it was possible to do this anyway, though it was laborious to do so.

These functions are:

DATEFROMPARTS ( year, month, day )
Returns a date value for the year, month, and day passed as parameters.
DATETIME2FROMPARTS ( year, month, day, hour, minute, seconds, fractions, precision )
Returns a datetime2 value for the date and time that you specify, with the specified precision.
DATETIMEFROMPARTS ( year, month, day, hour, minute, seconds, milliseconds )
# Returns a datetime value for the specified date and time.
DATETIMEOFFSETFROMPARTS ( year, month, day, hour, minute, seconds, fractions, hour_offset, minute_offset, precision )
Returns a datetimeoffset value for the parts you specify, with the specified offsets and precision.
SMALLDATETIMEFROMPARTS ( year, month, day, hour, minute )
Returns a smalldatetime value for the specified date and time.
TIMEFROMPARTS ( hour, minute, seconds, fractions, precision )
Returns a time value for the specified time and with the specified precision.

Implicit conversion from the presentation format of a data into a storage form can cause problems. Dates can be coerced into the Datatype by assigning string values to variables or columns, but these are usually affected by the DATEFORMAT stored for the particular language that is current. The order in which the month (m), day (d), and year (y) is written is different in other countries. US_English (mdy) is different from british (dmy). By explicitly setting the date format you can over-ride this.

You can check your current DATEFORMAT, amongst other things by using:

Any date representation based on words (e.g. febbraio, fevereiro, february) will fail in any other language that uses a different word for a given month. To see the current language settings, use:

Nations have different conventions for representing the date as a numerical string. This is why the default DATEFORMAT changes as you change the language.

SET DATEFORMAT is used to override this for the current connection. It will change the order in which you supply the day, month and year in the date as a string, from the default for your language setting. It can take one of the following strings ‘mdy’, ‘dmy’, ‘ymd’, ‘ydm’, ‘myd’, and ‘dym’ (‘ydm’ won’t work with the DATE, DATETIME2 and DATETIMEOFFSET datatypes).

Whereas if you get the DATEFORMAT wrong….

If you need dates to be understood internationally, then you need to use the data-interchange format.

DATEFORMAT has no effect if you format your dates in a standard way.

So this is the safest way to import date strings, especially when you consider that SQL Server 2008’s DATE, DateTime2 and Datetimeoffset work differently with ANSI SQL Standard strings.

Otherwise SQL Server is fairly accommodating, and will do its best to make sense of a date. All of the following return 2012-02-01 00:00:00.000

If you use the CONVERT function, you can override the DATEFORMAT by choosing the correct CONVERT style (103 is the British/French format of dd/mm/yyyy (see later for a list of all the styles)

The CONVERT function gives you a great deal of control over the import of dates in string form, since one can specify the expected format, and is probably the best way of importing dates via a data feed, if the dates aren’t in the ISO or ODBC format.

The IsDate function

The IsDate(expression) function is used for checking strings to see if they are valid dates. It is language-dependent.

ISDATE (Expression) returns 1 if the expression is a valid date (according to the language and DATEFORMAT mask) and 0 if it isn’t. The following demonstration uses ISDATE to test out the input of strings as dates.

Inputting Times

Times can be input into SQL Server just as easily. Until SQL Server 2008, there were no separate time and date types for storing only times or only dates. It was not really necessary. If only a time is specified when setting a datetime, the date is assumed to be the first of January 1900, the year of the start of the last millennium. If only a date is specified, the time defaults to Midnight. With SQL Server 2008, we now have the DATE and TIME Data-Types, which make the use of dates and times less idiosyncratic.

You can input times a different ODBC-standard way (note that the brackets are curly braces.

…which unexpectedly gives 09.40 today, rather than 9:40 on the first of January 1900! (as one might expect from the other time input examples). This is valid in a stored procedure too.

Outputting dates

Dates can be output as strings in a number of ways using the CONVERT function together with the appropriate CONVERT styles These styles are numeric codes that correspond with the most popular date formats. You get much more versatility with the CONVERT function than the CAST function.

The CONVERT styles override the setting of the DATEFORMAT but use the current language setting where the date format uses the name of the month. If you run the following code you will get a result that illustrates all the built-in formats for your particular language settings etc. , using the current date and time

294-294-robynP1.gif

Data in SQL Server 2012 onwards can use the format() function that allows you to use .NET’s formatting facilities, which are rather different to the pre-existing SQL Server methods.  For dates there are a number of standard formats, as can easily be demonstrated.

Manipulating dates

Getting the current date can be done by five functions:

When extracting parts of a DateTime you have some handy functions that return integers:

DAY, MONTH, YEAR
Here we get the day, month and year as integers.
SELECT DAY(GETDATE()),MONTH(GETDATE()),YEAR(GETDATE())
The functions DAY, MONTH and YEAR are shorter than the equivalent DATEPART command, but for more general use the DATEPART function is more versatile
SELECT DATEPART(DAY,GETDATE()),DATEPART(MONTH,GETDATE()), DATEPART(YEAR,GETDATE())
These work just as well with the other date/Time data types, of course
DATEADD

DATEADD will actually add a number of years, quarters, months, weeks, days, hours, minutes, seconds, milliseconds, microseconds or nanoseconds to your specified date. The format for this, and the other date-manipulation functions is as follows:

  • year (yy or yyyy)
  • quarter (qq or q)
  • month (mm or m)
  • week (wk or ww)
  • Day (dayofyear, dy, y, day, dd, d, weekday or dw)
  • hour (hh
  • minute (mi or n),
  • second (ss or s)
  • millisecond (ms)
  • microsecond (mcs) SQL Server 2008 or above only
  • nanosecond (ns) SQL Server 2008 or above only

In these examples we compare the date with the DATEADDed date so you can see the effect that the DATEADD is having to it

DATEDIFF

DATEDIFF returns an integer of the difference between two dates expressed in years, quarters, months, weeks, days, hours, minutes, seconds or milliseconds, microseconds or nanoseconds (it counts the boundaries).

We will give some practical examples of its use later on in the workbench.

DATENAME

Unlike DatePart, which returns an integer, DATENAME returns a NVarchar representing the year, quarter, month, week, day of the week, day of the year, hour, minute, second or millisecond within the date. The month and weekday are given in full from the value in the sysLanguages table.

DATEPART

DATEPART returns an integer representing the part of the date requested in the 1st parameter. You can use year ((yy or yyyy), quarter (qq or q), month (mm or m), dayofyear (dy or y) day (dd or d), week (wk or ww) , weekday (dw),hour (hh), minute (mi or n), second (ss or s), or millisecond (ms) */

Formatting Dates

Examples of calculating and formatting dates:

Calculating Dates by example

We can, of course, encapsulate all this into a function that will then give us the first, second, third or fourth occurrence of any day of the week in any month of any year perfectly easily.

Date Conversions

When converting from SQL Server dates to Unix timestamps, the dates are rounded to the nearest second (Unix timestamps are only accurate to the nearest second) SQL Server date to Unix timestamp (based on seconds since standard epoch of 1/1/1970).

The newer datatypes can give some fascinating information. Here is an instant way of finding what the current time and date is, in a variety of parts of the world.

294-294-robynP2.gif

We’ve put a fuller version of this script in the downloads at the bottom of the article.

Using dates

When storing dates, always use one of the date/time data types. Do not feel tempted to use tricks such as storing the year, month or day as integers, with the idea that this will help retrieval and aggregation for reports. It never does.

if you use the DATETIMEOFFSET, you are reasonably future-proof as you store dates as the UTC date together with the offset. This means that you can do dime-and-date calculations on data, even if it has been taken from more than one time zone.

The manipulation of the date/time data types is so critical to SQL Server’s performance that it is highly optimised. indexes based on date/time data type work very well, sort properly, and allow fast partitioning on a variety of criteria such as week, month, year-to-date and so on.

If, for example, you store a list of purchases by date in a table such as PURCHASES you can find the sum for the previous week by:

This LIKE trick is of limited use and should be used with considerable caution as it uses artifice to get its results.

More complicated Date calculations

So now some more complicated stuff. Here is how you calculate Easter:

And now for something slightly different, how could one calculate the sort of calculator that appears when you need to input a date (This can be used for some types of management reports where daily sales volumes need to be tracked.)

294-img73.jpg

If you spot a mistake or an omission, or you think of another useful date calculation, please let the editor know and we’ll get the article updated.

How you log in to Simple Talk has changed

We now use Redgate ID (RGID). If you already have an RGID, weโ€™ll try to match it to your account. If not, weโ€™ll create one for you and connect it.

This wonโ€™t sign you up to anything or add you to any mailing lists. You can see our full privacy policy here.

Continue

Simple Talk now uses Redgate ID

If you already have a Redgate ID (RGID), sign in using your existing RGID credentials. If not, you can create one on the next screen.

This wonโ€™t sign you up to anything or add you to any mailing lists. You can see our full privacy policy here.

Continue