Share via

Strange CONVERT behaviour

Josh Ashwood 96 Reputation points
2023-07-26T13:33:29.5+00:00

SELECT CONVERT(datetime, '01JAN2022', 103)

Can anyone explain to me how the above code works without error and returns '2022-01-01 00:00:00.000' when the specified style for 103 is dd/mm/yyyy ?

Shouldn't this code error?

SQL Server | Other
SQL Server | Other

Additional SQL Server features and topics not covered by specific categories

0 comments No comments

Answer accepted by question author

Erland Sommarskog 134.7K Reputation points MVP Volunteer Moderator
2023-07-26T21:09:53.48+00:00

I find that

SELECT CONVERT(datetime, '20221114', 103)

also works. To note here is that YYYYMMDD is a "safe" format which is always interpreted in the same way.

I guess that the conversion considers all formats, no matter the code. But if the format is an ambiguous one, the style code is used to force the interpretation. For instance:

SELECT CONVERT(datetime, '2022-04-06', 103)

returns 2022-06-04 00:00:00.000. Because with dmy format, SQL Server interprets this format as ydm.

By the way, I did not now that the format 01JAN2022 (without any spaces) would convert at all!

Was this answer helpful?


1 additional answer

Sort by: Most helpful
  1. Yitzhak Khabinsky 27,196 Reputation points
    2023-07-26T14:11:30.5466667+00:00

    Hi @Josh Ashwood,

    The CONVERT() function third parameter is a style for an input value to allow interpretation of the '01JAN2022'.

    SQL Server stores datetime value in a binary format internally. Its presentation is always in the ISO 8601 standard format, i.e yyyy-MM-dd hh:mm:ss.msec

    You can use FORMAT() function to convert datetime data type to a string with a desired format.

    Was this answer helpful?

    0 comments No comments

Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.