-2

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.

4

3 Answers 3

3

Assuming SQL Server:

DECLARE @A NVARCHAR(10)
SET @A = '11302012'

SELECT CONVERT(DATETIME,LEFT(@A,2) + '/' + 
       SUBSTRING(@A,3,2) + '/' + RIGHT(@A,4),101)
Sign up to request clarification or add additional context in comments.

Comments

0
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.

6 Comments

This is a lot of work when you can just use CONVERT
@njk - There isn't a CONVERT style for the mmddyyyy format, unless I'm missing something msdn.microsoft.com/en-us/library/ms187928.aspx
@LastCoder And wich one is it?
@Lamak - You're going to have to elaborate a bit.
The YYYY-MM-DD format isn't safe for implicit conversion to datetime. On the other hand, YYYYMMDD is, and so you could simplify your code down to just two SUBSTRING calls: SUBSTRING(@s, 5, 4) + SUBSTRING(@s, 1, 4).
|
0

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;

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.