Link to home
Start Free TrialLog in
Avatar of tim_cs
tim_csFlag for United States of America

asked on

Convert DateTime value

I'm uploading a flat file I recieve into a temp table.  A date in the file is in the format of 'dd-mm-yy' and is placed into a varchar field in the temp table.  Is the only way to convert this to an actual date in SQL by using SUBSTRING like below or is there a better way?  This is for SQL 2005.  

CAST(SUBSTRING(F1,4,2) + '-' + SUBSTRING(F1,1,2) + '-' + SUBSTRING(F1,7,2) AS datetime)

Open in new window

Avatar of Kevin Cross
Kevin Cross
Flag of United States of America image

No you can use the CONVERT() function also.  You just have to provide it with the format of the string in the field.
Forgot link to reference, but here is an example also.

It looks like you need the Italian format 105.
CONVERT(DATETIME, F1, 105)

Open in new window

http://msdn.microsoft.com/en-us/library/ms187928.aspx
ASKER CERTIFIED SOLUTION
Avatar of Kevin Cross
Kevin Cross
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
You may find following helpfull with Convert
http://www.w3schools.com/sql/func_convert.asp
Avatar of tim_cs

ASKER

Ha, I had been trying convert with 105 for a while and kept getting the conversion failed from character string which is why I switched to substring.  I had just realized I needed 5 instead of 105 when you posted mwvisa1.  Thank you!!
Hi,

Here is the good DateTime conversion to any Date format...

http://blog.sqlauthority.com/2008/08/14/sql-server-get-date-time-in-any-format-udf-user-defined-functions/

after you have created the sql function specified in the above link, try the below sample sql statements for your needed format.

eg.,

-- in your case input is dd-mm-yy (05-16-11)
SELECT [dbo].[ufsFormat] ('05-16-11', 'mm-dd-yyyy')      -- Output : 05-16-2011

SELECT [dbo].[ufsFormat] ('05-16-11', 'dd-mm-yyyy')      -- Output: 16-05-2011

SELECT [dbo].[ufsFormat] ('05-16-11', 'dd-mm-yy')       -- Output: 16-05-11

Open in new window

Try with this. it may help you.

Happy Programming.
Pinal Dave writes some very great stuff, but keep in mind the need here is to go from VARCHAR to DATETIME.  Pinal's UDF is going from DATETIME to a specific formatted VARCHAR.