65.9K
CodeProject is changing. Read more.
Home

Build a Date Function

starIconstarIconstarIconstarIconstarIcon

5.00/5 (2 votes)

Nov 26, 2012

CPOL

1 min read

viewsIcon

8321

This is an alternative for "Build a Date Function"

Introduction

Using the original tip I found that passing incorrect dates like dbo.fn_BuildDate( 2012, 11, 32 ); resulted in a date (2012-12-02) without any error messages, allowing the code to continue with an incorrect date.

So I made a function that gives an error when incorrect dates are passed to it. The quickest and easiest way I could find resulted in the following function.

CREATE FUNCTION [dbo].[fn_BuildDate] (@Year int, @Month int, @Day int)
RETURNS DATETIME
BEGIN
    RETURN CONVERT( DATETIME, CAST( @Year AS VARCHAR ) + RIGHT( '0' + CAST( @Month AS VARCHAR ), 2 ) + RIGHT( '0' + CAST( @Day AS VARCHAR ), 2 ), 112 )
END

Using the code 

Using the function has not changed:

DECLARE @StartDate Date
SET @StartDate = dbo.fn_BuildDate(2012,11,26)
But when an invalid date is passed:
DECLARE @StartDate Date
SET @StartDate = dbo.fn_BuildDate(2012,11,32)  
You get the following error message:
The conversion of a varchar data type to a datetime data type resulted in an out-of-range value.
The oldest date that can be used before getting an out-of-range error is:
DECLARE @StartDate Date
SET @StartDate = dbo.fn_BuildDate(1753,1,1)

Points of Interest  

For the conversion of the date string to datetime I used CONVERT[^] instead of CAST, because with the CONVERT statement it is possible to specify the style (112 for yyymmdd) of the string to be converted. Had I used a CAST then I would have had to make sure the date string looked like '2012-11-26', causing me to use a additional two string concatenations.  But more importantly this conversion is dependent on the NLS settings of the instance the function is being run on, so using CONVERT we determine the style of the string to be converted.

History

1. - Release
2. - As per Selvin's comments, the function failed for months and days smaller than 10. The function is updated to correctly process these inputs.