0

How can I convert this format to datetime? I'm using SQL Server 2008.

The string can be d/m/aaaa or dd/m/dddd or d/mm/aaaa or dd/mm/aaaa and I need to convert these formats to datetime. Any idea?

2
  • 1
    CONVERT(datetime, <yourstring>, 103) ? Commented Sep 29, 2017 at 8:48
  • Its works! thanks! Commented Sep 29, 2017 at 8:53

1 Answer 1

1

You can use CONVERT() as:

DECLARE @S1 VARCHAR(20) = '1-1-2017';
DECLARE @S2 VARCHAR(20) = '11/1/2017';
DECLARE @S3 VARCHAR(20) = '1/11/2017';
DECLARE @S4 VARCHAR(20) = '11/11/2017';


SELECT CONVERT(DATETIME, @S1 , 104) AS S1,
       CONVERT(DATETIME, @S2 , 104) AS S2,
       CONVERT(DATETIME, @S3 , 104) AS S3,
       CONVERT(DATETIME, @S4 , 104) AS S4;

Result:

+---------------------+---------------------+---------------------+---------------------+
|         S1          |         S2          |         S3          |         S4          |
+---------------------+---------------------+---------------------+---------------------+
| 01.01.2017 00:00:00 | 11.01.2017 00:00:00 | 01.11.2017 00:00:00 | 11.11.2017 00:00:00 |
+---------------------+---------------------+---------------------+---------------------+
Sign up to request clarification or add additional context in comments.

1 Comment

It works, but why do you have 104 as a parameter? It doesn't make sense to me, and it works without this additional parameter as well.

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.