I have a column of dates with no delimiters. The column is nvarchar. The strings are consistent in length and format of MMDDYYYY
. How can I convert these values to datetime
?
edit - this question is in reference to sql server.
I have a column of dates with no delimiters. The column is nvarchar. The strings are consistent in length and format of MMDDYYYY
. How can I convert these values to datetime
?
edit - this question is in reference to sql server.
Assuming SQL Server:
DECLARE @A NVARCHAR(10)
SET @A = '11302012'
SELECT CONVERT(DATETIME,LEFT(@A,2) + '/' +
SUBSTRING(@A,3,2) + '/' + RIGHT(@A,4),101)
BEGIN
DECLARE @d DATETIME
DECLARE @s NVARCHAR(32)
SET @s = N'12012013'
SET @d = SUBSTRING(@s, 5,4) + SUBSTRING(@s, 1,2) + SUBSTRING(@s, 3,2)
SELECT @d
END
You just have to mangle the string into a format SQL server can parse correctly into a date. In the above it's the YYYYMMDD format.
EDIT Removed "-"'s because French language settings break them.
First change the format to the one that always works no matter what server settings (YYYYMMDD) using two simple string functions, then convert to datetime:
declare @datestring varchar(8) = '11302012';
select CONVERT(datetime, RIGHT(@datestring, 4) + LEFT(@datestring, 4)) ConvertedDatetime;