The Butter Connection

aka "stanguru.com" and "themargerums.com"

Computer Tips & Help
AS400
PC
Hardware
Programming
Web Development
Virus
Spyware/Malware
Spam
Hoax Don't Spread It
Sports
Cancer
Multiple Sclerosis
Election Stuff
Photography
Handy Links
Interesting
Cool Things
Gamer Stuff
Gallery
Clarion · SQL · SQL Dates · SQL RPG examples · Batch Files

 

SQL Date Stuff

 

this part is from http://databasejournal.com/features/mssql/article.php/3076421

I copied it here just in case the page gets moved

 

September 15, 2003
Examples of how to Calculate Different SQL Server Dates

By Gregory A. Larsen

Every now and then, you need to take the current date and calculate some other date. For instance, you might have an application that needs to determine what date is the first day of the month, or need to know the last day of the month. Now most of you probably already know how to separate the date into its piece (year, month, day, etc.) and use those pieces along with a number of functions to calculate a date that you might need. In this article, I will be showing how to use just the DATEADD and DATEDIFF function to calculate a number of different dates you might need to use in your applications.

In order to understand these examples, let's first review the DATEDIFF and DATEADD functions. The DATEDIFF function calculates the amount of time between two dates, where the time part is based on an interval of time, such as hours, days, weeks, months, years, etc. The DATEADD function calculates a date by taking an interval of time, and adding it to a date, where the interval of time will be the same as those used by the DATEDIFF function. To find out more about the DATEDIFF and DATEADD functions, and the different intervals of time read Microsoft Books Online.

Using the DATEADD and DATEDIFF functions to calculated dates requires you to think a little differently about what it takes to convert the current date into a date you need. You must think in terms of date intervals. Such as, how many date intervals it is from the current date to the date you want to calculate. Or how many date intervals is it from today to some other date like '1900-01-01', and so on. Understanding how to look at date intervals will help you more easily understand my different date examples.

First Day of Month

For the first example, let me show you how to get the first day of the month from the current date. Remember now, this example and all the other examples in this article will only be using the DATEADD and DATEDIFF functions to calculate our desired date. Each example will do this by calculating date intervals from the current date, and then adding or subtracting intervals to arrive at the desired calculated date. Here is the code to calculate the first day of the month:

select DATEADD(mm, DATEDIFF(mm,0,getdate()), 0)

Let me review how this works, by breaking this statement apart. The inner most function call "getdate()", as most of you probably already know, returns the current date and time. Now the next executed function call "DATEDIFF(mm,0,getdate())" calculates the number of months between the current date and the date "1900-01-01 00:00:00.000". Remember date and time variables are stored as the number of milliseconds since "1900-01-01 00:00:00.000"; this is why you can specify the first datetime expression of the DATEDIFF function as "0." Now the last function call, DATEADD, adds the number of months between the current date and '1900-01-01". By adding the number of months between our pre-determined date '1900-01-01' and the current date, I am able to arrive at the first day of the current month. In addition, the time portion of the calculated date will be "00:00:00.000."

The technique shown here for calculating a date interval between the current date and the year "1900-01-01," and then adding the calculated number of interval to "1900-01-01," to calculate a specific date, can be used to calculate many different dates. The next four examples use this same technique to generate different dates based on the current date.

Monday of the Current Week

Here I use the week interval (wk) to calculate what date is Monday of the current week. This example assumes Sunday is the first day of the week.

select DATEADD(wk, DATEDIFF(wk,0,getdate()), 0)

If you don't want Sunday to be the first day of the week, then you will need to use a different method. Here is a method that David O Malley showed me that uses the DATEFIRST setting to set the first day of the week. This example sets Monday as the first day of the week, but by changing the DATEFIRST setting any day of the week could be the first day of the week.

set DATEFIRST 1

select DATEADD(dd, 1 - DATEPART(dw, getdate()), getdate())

First Day of the Year

Now I use the year interval (yy) to display the first day of the year.

select DATEADD(yy, DATEDIFF(yy,0,getdate()), 0)

First Day of the Quarter

If you need to calculate the first day of the current quarter then here is an example of how to do that.

select DATEADD(qq, DATEDIFF(qq,0,getdate()), 0)

Midnight for the Current Day

Ever need to truncate the time portion for the datetime value returned from the getdate() function, so it reflects the current date at midnight? If so then here is an example that uses the DATEADD and DATEDIFF functions to get the midnight timestamp.

select DATEADD(dd, DATEDIFF(dd,0,getdate()), 0)
yesterday SELECT     DATEADD(dd, DATEDIFF(dd, 0, GETDATE()), - 1) 

Expanding on the DATEADD and DATEDIFF Calculation

As you can see, by using this simple DATEADD and DATEDIFF calculation you can come up with many different dates that might be valuable.

All of the examples so far only calculated the current number of date intervals between the current date and "1900-01-01," and then added the number of intervals to "1900-01-01" to arrive at the calculated date. Say you modify the number of intervals to be added, or added additional DATEADD functions that used different time intervals, or subtracted intervals instead of adding intervals; by making these minor changes you can come up with many different dates.

Here are four examples that add an additional DATEADD function to calculate the last day dates for both the current and prior intervals.

Last Day of Prior Month

Here is an example that calculates the last day of the prior month. It does this by subtracting 3 milliseconds from the first day of the month example. Now remember the time portion in SQL Server is only accurate to 3 milliseconds. This is why I needed to subtract 3 milliseconds to arrive at my desired date and time.

select dateadd(ms,-3,DATEADD(mm, DATEDIFF(mm,0,getdate()  ), 0))

The time portion of the calculated date contains a time that reflects the last millisecond of the day ("23:59:59.997") that SQL Server can store.

Last Day of Prior Year

Like the prior example to get the last date of the prior year you need to subtract 3 milliseconds from the first day of year.

select dateadd(ms,-3,DATEADD(yy, DATEDIFF(yy,0,getdate()  ), 0))

Last Day of Current Month

Now to get the last day of the current month I need to modify slightly the query that returns the last day of the prior month. The modification needs to add one to the number of intervals return by DATEDIFF when comparing the current date with "1900-01-01." By adding 1 month, I am calculating the first day of next month and then subtraction 3 milliseconds, which allows me to arrive at the last day of the current month. Here is the TSQL to calculate the last day of the current month.

select dateadd(ms,-3,DATEADD(mm, DATEDIFF(m,0,getdate()  )+1, 0))

Last Day of Current Year

You should be getting the hang of this by now. Here is the code to calculate the last day of the current year.

select dateadd(ms,-3,DATEADD(yy, DATEDIFF(yy,0,getdate()  )+1, 0))

First Monday of the Month

Ok, I am down to my last example. Here I am going to calculate the first Monday of the current month. Here is the code for that calculation.

select DATEADD(wk, DATEDIFF(wk,0,
            dateadd(dd,6-datepart(day,getdate()),getdate())
			                            ), 0)      

In this example, I took the code for "Monday of the Current Week," and modified it slightly. The modification was to change the "getdate()" portion of the code to calculate the 6th day of the current month. Using the 6th day of the month instead of the current date in the formula allows this calculation to return the first Monday of the current month.

Conclusion

I hope that these examples have given you some ideas on how to use the DATEADD and DATEDIFF functions to calculate dates. When using this date interval math method of calculating dates I have found it valuable to have a calendar available to visualize the intervals between two different dates. Remember this is only one way to accomplish these date calculations. Keep in mind there are most likely a number of other methods to perform the same calculations. If you know of another way, great, although if you do not, I hope these examples have given you some ideas of how to use DATEADD and DATEDIFF to calculate dates your applications might need.

» See All Articles by Columnist Gregory A. Larsen

 

 

May 7, 2003
Working with SQL Server Date/Time Variables: Part Two - Displaying Dates and Times in Different Formats

By Gregory A. Larsen

In my first article in this series, I discussed different aspects of entering date/time data into SQL Server DATETIME and SMALLDATE columns. This article will expand my discussion of date/time data by exploring how to use different SQL Server functions to display dates and times in different formats.

Depending on your environment, your needs, and/or the audience of your application, the format for displaying date and time might vary. Internationally we have many difference ways to represent a given date and/or time. Here are a few examples of different ways we might display the date January 22, 2003 with or without a time of 10:31 PM.

  • 2003/01/22 10:31PM
  • 2003/01/22 22:31
  • 22-01-2003
  • 22 January 2003
  • Jan 22 2003 10:13PM
  • January 22, 2003

Let's review the SQL Server functions that can be used to display these date formats, starting with the CONVERT function. The CONVERT function is provided to help with converting a DATETIME or SMALLDATETIME variables, or any other string that holds a valid date, into different date/time display formats. The CONVERT function is called using the following syntax:

	CONVERT ( data_type [ ( length) ] , expression [ , style ] )  

Where data_type [(length)] is the target data type format and length, expression is any valid Microsoft expression that represents the date/time you want to display, and style specifies the output format for the data/time.

Using the CONVERT function, with different styles, allows you to display date and time data in many different formats. Let's look at what I am taking about. The easiest way to demonstrate how to use the CONVERT function is to review some TSQL code that displays the current time in a few different display formats. The following script uses only the CONVERT function to display the different formats.

PRINT '1) HERE IS MON DD YYYY HH:MIAM (OR PM) FORMAT ==>' + 
CONVERT(CHAR(19),GETDATE())  
PRINT '2) HERE IS MM-DD-YY FORMAT ==>' + 
CONVERT(CHAR(8),GETDATE(),10)  
PRINT '3) HERE IS MM-DD-YYYY FORMAT ==>' + 
CONVERT(CHAR(10),GETDATE(),110) 
PRINT '4) HERE IS DD MON YYYY FORMAT ==>' + 
CONVERT(CHAR(11),GETDATE(),106)
PRINT '5) HERE IS DD MON YY FORMAT ==>' + 
CONVERT(CHAR(9),GETDATE(),6) 
PRINT '6) HERE IS DD MON YYYY HH:MM:SS:MMM(24H) FORMAT ==>' + 
CONVERT(CHAR(24),GETDATE(),113)

Here is the output from the above script:

1) HERE IS MON DD YYYY HH:MIAM (OR PM) FORMAT ==>Feb  5 2003  5:54AM
2) HERE IS MM-DD-YY FORMAT ==>02-05-03
3) HERE IS MM-DD-YYYY FORMAT ==>02-05-2003
4) HERE IS DD MON YYYY FORMAT ==>05 Feb 2003
5) HERE IS DD MON YY FORMAT ==>05 Feb 03
6) HERE IS DD MON YYYY HH:MM:SS:MMM(24H) FORMAT ==>05 Feb 2003 05:54:39:567

As you can see, this script displays the current date in many different formats. Some formats have two digit years, while others have four digit years. Some displays have 24 hour or AM/PM time formats. Still others have the month displayed as a numeric value, while others have a month abbreviation. Some of the displays also have the date displayed in DD MON YYYY format. I suggest you review Books Online for a description of all the formats that the CONVERT function can display using different styles.

Even though the CONVERT function has a number of data/time output styles, it still might not have the exact display format you need to display. Sometimes you will need to use other TSQL functions as well, to get the display format you desire.

Another important date/time function worth describing is DATEPART. This function will take a date/time expression and return a single part of the date, such as hour, minute, month, day, etc. A call to this function has the following form:

	DATEPART(datepart, date)>

Where the datepart is one of the following: Year, yy, yyyy, quarter, qq, q, month, mm, m, dayofyear, dy, y, day, dd, d, week, wk, ww, weekday, dw,hour, hh, minute, mi, n, second, ss, s, millisecond, or ms. And date is a valid date expression. This function will return an integer representing the particular date part requested.

Let's review how the CONVERT and/or DATEPART functions can be used to display January 22, 2003 with a time of 10:31 PM to meet all of the display formats I showed at the top of this article.

Some of the formats can be created using the different "style" options on the CONVERT statement. Although a number of these formats above will not only require the CONVERT and/or DATEPART functions, but other TSQL functions like SUBSTRING, RIGHT, and CAST to build the desired display format. If you are unfamiliar with these additional functions, read Books Online for more information. To show you how to create each of these display formats I will build a simple script for each of the different formats.

 

May 7, 2003
Working with SQL Server Date/Time Variables: Part Two - Displaying Dates and Times in Different Formats

By Gregory A. Larsen

The first example displays the date in 2003/01/22 10:13PM format. This can be done with the following simple script that uses the CONVERT and SUBSTRING functions. Note this example uses the 111 style format of the CONVERT function.

DECLARE @DT DATETIME
SET @DT = '2003-01-22 10:31 PM'
SELECT CONVERT(CHAR(11),@DT,111) + 
SUBSTRING(CONVERT(CHAR(19),@DT,100),13,19)

Normally there is always more than one way to get the same results. Here is another way to get the same date displayed by using the DATEPART, CAST and RIGHT functions:

DECLARE @DT DATETIME
SET @DT = '2003-01-22 10:31 PM'
SELECT CAST(DATEPART(YYYY,@DT) AS CHAR(4)) + '/' 
     + RIGHT(CAST(100+DATEPART(MM,@DT) AS CHAR(3)),2) + '/'
     + RIGHT(CAST(100+DATEPART(DD,@DT) AS CHAR(3)),2) + ' '
     + CASE WHEN DATEPART(HH,@DT) < 13 
            THEN RIGHT(CAST(100+DATEPART(HH,@DT) AS CHAR(3)),2) 
            ELSE CAST(DATEPART(HH,@DT)-12 AS CHAR(2)) 
            END + ':'
     + RIGHT(CAST(100+DATEPART(MI,@DT) AS CHAR(3)),2)     
     + CASE WHEN DATEPART(HH,@DT) < 13
            THEN 'AM'
            ELSE 'PM'
            END

The next example will display the date in 2003/01/22 22:31 format. This example uses the REPLACE function to convert the dashes, of CONVERT style 120, to slashes.

DECLARE @DT DATETIME
SET @DT = '2003-01-22 10:31 PM'
SELECT REPLACE(CONVERT(CHAR(16),@DT,120),'-','/')

The following example will display the date in 22-01-2003 format, without the time portion. To display only the date portion and truncate the time part, I specified an output data type and length. In the example below a CHAR(10) was used for data type and length. This will cause the CONVERT function to display only the first 10 characters of style 105.

DECLARE @DT DATETIME
SET @DT = '2003-01-22 10:31 PM'
SELECT CONVERT(CHAR(10),@DT,105)

The next example displays the date using 22 January 2003 format. To produce this date output, I will introduce a new function, DATENAME. The DATENAME function returns a character string representing the requested part of the date. The DATENAME function uses the following syntax:

	DATENAME( datepart , date )

Where the datepart is one of the following: Year, yy, yyyy, quarter, qq, q, month, mm, m, dayofyear, dy, y, day, dd, d, week, wk, ww, weekday, dw,hour, hh, minute, mi, n, second, ss, s, millisecond, or ms, and date is a valid date expression. This function will return a character string representing the particular date part requested. Be aware that the "weekday" parm returns the day name, like Sunday, Monday, Tuesday, etc, and the "month" parm returns the month name, like January, February, March, etc. This example uses DATENAME to return the DAY, MONTH and YEAR of the variable @DT. The month portion of the date will be returned with the spelled out version of the month, or in this case "January."

DECLARE @DT DATETIME
SET @DT = '2003-01-22 10:31 PM'
SELECT DATENAME(DAY,@DT) + ' ' + DATENAME(MONTH,@DT) + ' ' + DATENAME(YEAR, @DT)

The CONVERT function alone allows me to output a date with Jan 22 2003 10:13PM format. By using a style of 100, the CONVERT function displays the date format needed.

DECLARE @DT DATETIME
SET @DT = '2003-01-22 10:31 PM'
SELECT CONVERT(CHAR(19),@DT,100)

To display a date in January 22, 2003 format I will again use the DATENAME function, I just change the output formatting, by rearranging the calls for each date part.

DECLARE @DT DATETIME
SET @DT = '2003-01-22 10:31 PM'
SELECT DATENAME(MONTH,@DT) + ' ' + DATENAME(DAY,@DT) + ', ' + DATENAME(YEAR, @DT)

Three more SQL Server functions that might help you with formatting date output are worth mentioning. These functions are DAY, MONTH, and YEAR. Each of these functions accepts a date expression, and returns an integer value representing the day, month or year depending on which function is being called. Here is an example of how these functions are used to return a date in 01/22/2003 format.

DECLARE @DT DATETIME
SET @DT = '2003-01-22 10:31 PM'
SELECT '0' + CAST(MONTH(@DT) AS CHAR(1)) + '/' + CAST(DAY(@DT) AS 
CHAR(2)) + '/' + CAST(YEAR(@DT) AS CHAR(4))

Conclusion

There are many different way to display a given date and time value. Because of this, SQL Server provides the CONVERT function to format date/time values into a number of preset output formats. Also by using the CONVERT function along with one or more additional SQL Server functions, such as DATEPART you should be able to display the date any way you need.

My next article in this date/time series will discuss searching SQL Server tables to find records based on a date and time value.

» See All Articles by Columnist Gregory A. Larsen

 

 

Without century (yy) With century (yyyy)
Standard

Input/Output**
- 0 or 100 (*) Default mon dd yyyy hh:miAM (or PM)
1 101 USA mm/dd/yy
2 102 ANSI yy.mm.dd
3 103 British/French dd/mm/yy
4 104 German dd.mm.yy
5 105 Italian dd-mm-yy
6 106 - dd mon yy
7 107 - Mon dd, yy
8 108 - hh:mm:ss
- 9 or 109 (*) Default + milliseconds mon dd yyyy hh:mi:ss:mmmAM (or PM)
10 110 USA mm-dd-yy
11 111 JAPAN yy/mm/dd
12 112 ISO yymmdd
- 13 or 113 (*) Europe default + milliseconds dd mon yyyy hh:mm:ss:mmm(24h)
14 114 - hh:mi:ss:mmm(24h)
- 20 or 120 (*) ODBC canonical yyyy-mm-dd hh:mi:ss(24h)
- 21 or 121 (*) ODBC canonical (with milliseconds) yyyy-mm-dd hh:mi:ss.mmm(24h)
- 126(***) ISO8601 yyyy-mm-dd Thh:mm:ss.mmm(no spaces)
- 130* Hijri**** dd mon yyyy hh:mi:ss:mmmAM
- 131* Hijri**** dd/mm/yy hh:mi:ss:mmmAM


 


You are here: Home-Computer Tips & Help-Programming-SQL Dates

Previous Topic: SQL Next Topic: SQL RPG examples