Quantcast
Channel: TechNet Blogs
Viewing all articles
Browse latest Browse all 36188

How to avoid text-to-date conversion mismatches

$
0
0

 

In one of our previous posts we saw how different set options can affect execution plans and result sets.
Now let's see how to write our code in order to avoid text-to-date conversion mismatches.

In this example we can see one string being converted to two different dates:

 

set languageus_english
selectcast('11/12/2012'as datetime)

Result: 2012-11-12 00:00:00.000 -> November 12th 2012
 
set languagepolski
selectcast('11/12/2012'as datetime)

Result: 2012-12-11 00:00:00.000 -> December 11th 2012

 

The difference is caused by default dateformat for different languages.
The same problem happens for all date data types: smalldatetime, datetime, date, datetime2, datetimeoffset.

 

The only way to make sure casting is culture independent is to supply date string in one of following formats:

YYYYMMDD without forward or backward slashes or dashes (/ \ -) with or without time
example:


set languageus_english
selectcast('20121112'as datetime)

Result: 2012-11-12 00:00:00.000 -> November 12th 2012

set languagepolski
selectcast('20121112'as datetime)
Result: 2012-11-12 00:00:00.000 -> November 12th 2012

YYYY-MM-DDThh:mi:ss without spaces
example:

set languageus_english
selectcast('2012-11-12T00:00:00'as datetime)

Result: 2012-11-12 00:00:00.000 -> November 12th 2012

set languagepolski
selectcast('2012-11-12T00:00:00'as datetime)

Result: 2012-11-12 00:00:00.000 -> November 12th 2012

 

My personal favorite is the first one as it look much more readable and doesn't have to include time.


Viewing all articles
Browse latest Browse all 36188

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>