I need to convert a nvarchar
value to datetime
in T-SQL. The value is in ddmmyyyy
format, e.g. 23072009
I need t
Change VARCHAR (dd-mm-yyyy) to date (yyyy-mm-dd) in SQL Server.
DECLARE @VarDate VARCHAR(10)
SET @VarDate = '22-02-1994'
SELECT CONVERT(DATETIME, CONVERT(VARCHAR, CONVERT(DATE, @VarDate, 103), 102))
Format 103 expects dd/mm/yyyy
. (see here)
I don't think you'll be able to do it using convert, as non of the convert options have that format.
You can define custom function like this:
CREATE FUNCTION [dbo].[GetCustomDate] (@customDateString NVARCHAR(MAX))
RETURNS DATETIME
AS
BEGIN
RETURN CONVERT(DATETIME, RIGHT(@customDateString, 4) + RIGHT(LEFT(@customDateString, 4), 2) + LEFT(@customDateString, 2))
END
You need to cast a string and not a int. Put some quotes:
convert(datetime, '23072009', 103)
And 103 gets the string like 'dd/mm/yyyy' and not 'ddmmyyyy'.
The style 103 will accept strings with dd/mm/yyyy format. So your code should be
declare @date varchar(8)
set @date='23072009'
select convert(datetime,stuff(stuff(@date,5,0,'/'),3,0,'/') , 103)
Rebuild your format to yyyymmdd
.
declare @D varchar(8)
set @D = '23072009'
select cast(right(@D, 4)+substring(@D, 3, 2)+left(@D, 2) as datetime)