0

I've got some dates stored in varchar(10) format.

Dates are like so:

2008-01-06
2008-01-13
2008-01-20
2008-01-27
2008-02-03
2008-02-10
2008-02-17
2008-02-24

I would like them in dd/mm/yyyy format (also a DATE datatype)

I have tried the following:

SELECT CONVERT(VARCHAR(max), startWeek, 103) date
FROM dbo.GoogledataFinal

Why does this output:

2008-01-06
2008-01-13
2008-01-20
2008-01-27
2008-02-03
2008-02-10
2008-02-17

Would be great if you could fix my code, but I'm more interested in WHY this behaviour is happening, so explaining like I'm 5 years old might be helpful.

0

4 Answers 4

5

You are converting from varchar to varchar. The style parameter is not even used for that.

Instead, convert to date, and then back to varchar:

select convert(varchar(10), cast('2008-01-06' as datetime), 103)

This prints:

06/01/2008
Sign up to request clarification or add additional context in comments.

2 Comments

Many thanks, I always hated working with dates in SQL... Wondered what the differences with cast and convert where but this helps. Problem is fixed. Thanks.
@waller convert allows you to pass a formatting mask, which is important to handle strings representing dates.
2
SELECT CONVERT(varchar(10), CONVERT(datetime, startWeek), 103) date
FROM dbo.GoogledataFinal

1 Comment

you should really include a length on your varchar
0

Try this:

SELECT (SUBSTRING (startWeek,9, 2) + '/' + SUBSTRING (startWeek,6, 2) + '/' SUBSTRING (startWeek,1, 4))  AS date
FROM dbo.GoogledataFinal

Comments

0

You need to convert the varchar to a datetime, and then back to varchar using the desired format:

SELECT CONVERT( varchar(10), 
         CONVERT(DATETIME, '2008-02-03', 120) -- Varchar "yyyy-mm-dd" to Datetime
       , 103) -- Datetime to Varchar "dd/mm/yyyy"

For your case the SQL might be:

SELECT CONVERT( varchar(10), 
         CONVERT(DATETIME, startWeek, 120)
       , 103)
FROM dbo.GoogledataFinal

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.