Dynamically,convert,date,userdefined,format
Quick Search for:  in language:    
Dynamically,convert,date,userdefined,format
   Code/Articles » |  Newest/Best » |  Community » |  Jobs » |  Other » |  Goto » | 
CategoriesSearch Newest CodeCoding ContestCode of the DayAsk A ProJobsUpload
SQL Stats

 Code: 28,909 lines
 Jobs: 440 postings

 
Sponsored by:

 

You are in:

 
Login



Latest Code Ticker for SQL.
Link_SQLServer_ Oracle
By Daniel G. Menendez on 8/20


SQL Strip Alpha/Numeric
By Jay Gardner on 8/19


how to apply a filter to an Access 2000 form by using a combo box as a filter parameter
By David Nishimoto on 8/16


Click here to put this ticker on your site!


Add this ticker to your desktop!


Daily Code Email
To join the 'Code of the Day' Mailing List click here!





Affiliate Sites



 
 
   

FormatDate

Print
Email
 

Submitted on: 5/22/2002 4:35:10 PM
By: Lewis Moten  
Level: Intermediate
User Rating: By 4 Users
Compatibility:SQL Server 7.0

Users have accessed this article 2651 times.
 

(About the author)
 
     Dynamically convert a date to a user-defined format.

This article has accompanying files

 
 
Terms of Agreement:   
By using this article, you agree to the following terms...   
1) You may use this article in your own programs (and may compile it into a program and distribute it in compiled format for languages that allow it) freely and with no charge.   
2) You MAY NOT redistribute this article (for example to a web site) without written permission from the original author. Failure to do so is a violation of copyright laws.   
3) You may link to this article from another website, but ONLY if it is not wrapped in a frame. 
4) You will abide by any additional copyright restrictions which the author may have placed in the article or article's description.

Background:

 

MS SQL Server gives a limited range of formatting dates.  This range depends on converting data types by assigning a numbered style rather then a character representation. 

 

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

 

CAST and CONVERT (msdn link)

 

Another option that SQL Server exposes is the SET DATEFORMAT property.

 

SET DATEFORMAT { format | @format_var }

 

SET DATEFORMAT (msdn link)

 

This format is friendlier; in that you can actually tell what format it is trying to set just by looking at it.  Valid parameters include mdy, dmy, ymd, ydm, myd, and dym. The U.S. English default is mdy.

 

Goal:

 

My goal is to create a dynamic method of defining the format of a date that is common with other programs.  The code must be available within a function for use within SELECT statements.  The code must be small and quick.

 

Defining the format:

 

For this exercise, I looked at the date picker control that Microsoft offers.  Here are a few links to the MSDN library to help get you started:

 

FORMAT_STRING Contents

OutputFormat Property

Date Time String Transformation

 

From these pages, and many others, I identified to most basic formats and compiled a list. 

 

D

The one-digit of the two-digit day.

DD

The two-digit day.  A zero precedes single-digit day values.

DDD

The three-character weekday abbreviation.

DDDD

The full weekday name.

H

The one-digit or the two-digit hour in 12-hour format.

HH

The two-digit hour in 12-hour format.  A zero precedes single-digit values.

HHH

The one-digit or the two-digit hour in 24-hour format.

HHHH

The two-digit hour in 24-hour format.  A zero precedes single-digit values.

N

The one-digit or the two-digit minute.

NN

The two-digit minute.  A zero precedes single-digit values.

M

The one-digit or the two-digit month number.

MM

The two-digit month number.  A zero precedes single-digit values.

MMM

The three-character month abbreviation.

MMMM

The full month name.

T

The one-letter A.M. and P.M. Abbreviation (That is, “AM” is displayed as “A”)

TT

The two-letter A.M. and P.M. abbreviation (that is, “AM” is displayed as “AM”)

Y

The year is displayed as the last two digits, but with no leading zero for any year that is less than 10.

YY

The last two digits for the year.  For example, 1998 would be displayed as “98”

YYY

The full year.  For example, 1998 would be displayed as “1998”.

 

I found it hard to work with some of the formats because most installations of SQL Server to not recognize case-sensitivity. In this case, I simply added more letters.  For example, a 12-hour format would be a lower-case “H”, where as a 24 hour format would be an upper case “H”.  For the 24-hour representation, I added more “H” characters.

 

Retrieving Values:

 

The next problem I tackled was populating the values with the date provided.  I would populate the day, the hour, the year, and so on.  I was ignoring what the format wanted to be passed back.  Most values were obtained by using the DATEPART function.  Rather then storing the values as numbers, I “Casted” them as VarChars.  This allowed me to continue playing with them as strings and to use them in string related functions.  One of the tricks I used most was the RIGHT function to get two-digit numbers preceded with zeros.

 

            SET @d = CAST(DATEPART(d, @Date) AS VARCHAR(2))

            SET @dd = RIGHT('0' + @d, 2)

 

Another function I used was the DATENAME to grab the name of the month.  For abbreviations of the month, I selected the LEFT 3 characters.

 

            SET @MMMM = DATENAME(m, @Date)

            SET @MMM = LEFT(@MMMM, 3)

 

Preparing the Format:

 

The format string has the ability to contain other characters then the name of the month, hour, day, etc.  For example, you may want to format the time as “HH:NN” with a colon in between.  To support this, I replace each recognized format with a temporary place holder.

 

            SET @Format = REPLACE(@Format, 'dddd', '\\\\1\\\\')

            SET @Format = REPLACE(@Format, 'ddd', '\\\\2\\\\')

            SET @Format = REPLACE(@Format, 'dd', '\\\\3\\\\')

            SET @Format = REPLACE(@Format, 'd', '\\\\4\\\\')

 

I began with the largest repetitive characters first, and worked my way down.  The reason these place holders are needed is due to the fact that some months, may contain recognized formats.  Take the month of “May” for example.  The letter “M” is recognized to be a format for a single and two-digit number of the month.  If I were to replace the “mmmm” format first, and then apply the “m” format -- I would end up with “5ay”.

 

Applying the Format:

 

Applying was much quicker and appeared like so:

 

            SET @Format = REPLACE(@Format, '\\\\1\\\\', @dddd)

            SET @Format = REPLACE(@Format, '\\\\2\\\\', @ddd)

            SET @Format = REPLACE(@Format, '\\\\3\\\\', @dd)

            SET @Format = REPLACE(@Format, '\\\\4\\\\', @d)

 

I simply reversed the process and replace the placement markers with the values I retrieved earlier.

 

In the end, all that was left to do was return the format passed –

 

            return(@Format)

 

Next, I created a test to see if it would work

 

            PRINT dbo.FormatDate(GETDATE(), ‘MM/DD/YY HH:NN TT’)

 

And the result …

 

            05/22/2002 07:15 PM

 

This sums up my adventure with T-SQL programming.  If you find this information useful, please let others know.  Personal information about myself can be found on my personal website at http://www.lewismoten.com

 

winzip iconDownload article

Note: Due to the size or complexity of this submission, the author has submitted it as a .zip file to shorten your download time. Afterdownloading it, you will need a program like Winzipto decompress it.

Virus note:All files are scanned once-a-day by Planet Source Code for viruses,but new viruses come out every day, so no prevention program can catch 100% of them.

FOR YOUR OWN SAFETY, PLEASE:
1)Re-scan downloaded files using your personal virus checker before using it.
2)NEVER, EVER run compiled files (.exe's, .ocx's, .dll's etc.)--only run source code.

If you don't have a virus scanner, you can get one at many places on the net including:McAfee.com

 
Terms of Agreement:   
By using this article, you agree to the following terms...   
1) You may use this article in your own programs (and may compile it into a program and distribute it in compiled format for languages that allow it) freely and with no charge.   
2) You MAY NOT redistribute this article (for example to a web site) without written permission from the original author. Failure to do so is a violation of copyright laws.   
3) You may link to this article from another website, but ONLY if it is not wrapped in a frame. 
4) You will abide by any additional copyright restrictions which the author may have placed in the article or article's description.


Other 26 submission(s) by this author

 

 
Report Bad Submission
Use this form to notify us if this entry should be deleted (i.e contains no code, is a virus, etc.).
Reason:
 
Your Vote!

What do you think of this article(in the Intermediate category)?
(The article with your highest vote will win this month's coding contest!)
Excellent  Good  Average  Below Average  Poor See Voting Log
 
Other User Comments
5/23/2002 4:14:11 PM:sdinning
very clever use of "replace" function to return desired date format
Keep the Planet clean! If this comment was disrespectful, please report it:
Reason:

 
7/17/2002 12:27:56 PM:Rick Toner
OUTSTANDING!!! This is exactly what I was looking for. This will save me a lot of time in the future on trying to format my Dates.
Keep the Planet clean! If this comment was disrespectful, please report it:
Reason:

 
7/17/2002 1:16:11 PM:Lewis Moten
Glad I could help. Personally - I was getting sick and tired of the inconvienient options provided to format dates.
Keep the Planet clean! If this comment was disrespectful, please report it:
Reason:

 
Add Your Feedback!
Note:Not only will your feedback be posted, but an email will be sent to the code's author in your name.

NOTICE: The author of this article has been kind enough to share it with you.  If you have a criticism, please state it politely or it will be deleted.

For feedback not related to this particular article, please click here.
 
Name:
Comment:

 

Categories | Articles and Tutorials | Advanced Search | Recommended Reading | Upload | Newest Code | Code of the Month | Code of the Day | All Time Hall of Fame | Coding Contest | Search for a job | Post a Job | Ask a Pro Discussion Forum | Live Chat | Feedback | Customize | SQL Home | Site Home | Other Sites | About the Site | Feedback | Link to the Site | Awards | Advertising | Privacy

Copyright© 1997 by Exhedra Solutions, Inc. All Rights Reserved.  By using this site you agree to its Terms and Conditions.  Planet Source Code (tm) and the phrase "Dream It. Code It" (tm) are trademarks of Exhedra Solutions, Inc.