convert to datetime

johnson1
johnson1 used Ask the Experts™
on
How can I convert the string '31.5.2016 00:00:00' to date time.
If I do
SELECT CONVERT(datetime,'31.5.2016 00:00:00)
I get the error:
The conversion of a varchar data type to a datetime data type resulted in an out -of-range value.
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Senior Security and Infrastructure Engineer
Commented:
Specify the date & time in ISO 8601 format:
SELECT CONVERT(datetime,'2016-05-31T00:00:00')
ISO 8601 is always a good idea as it's easy to remember (largest unit to smallest), easy to read, and avoids any confusion over non-US/US date formatting (i.e. day before month vs month before day).
If this is SQL-Server, I think you are missing last parameter. CONVERT has 3 parameters, and the third specifies the format.
https://msdn.microsoft.com/en-us/library/ms187928%28v=sql.120%29.aspx
Robin CMSenior Security and Infrastructure Engineer
Commented:
The third parameter for CONVERT (date_style smallint) is optional.
Expert Spotlight: Joe Anderson (DatabaseMX)

We’ve posted a new Expert Spotlight!  Joe Anderson (DatabaseMX) has been on Experts Exchange since 2006. Learn more about this database architect, guitar aficionado, and Microsoft MVP.

Yes, it is optional but I would recommend to use it in order to "explain" to the computer what kind of format are you using on the string.
Scott PletcherSenior DBA
Most Valuable Expert 2018
Top Expert 2014
Commented:
Just CAST it.  CAST is more flexible in that it will accept any valid format without you having to provide a specific code for it:

SELECT CAST('31.5.2016 00:00:00' AS datetime)
Yes, but the problem is that some dates as 3/2/2015 could be read as febrary the 3th of 2015 or as march the 2nd of 2015. So I think it is a good idea to provide which format are you using to avoid ambiguosities
Scott PletcherSenior DBA
Most Valuable Expert 2018
Top Expert 2014
Commented:
Local date settings take care of that.  CAST is the way to go unless you have to use CONVERT.
Yes, but if you relay of local date settings, what happens when you run the program on another computer? What if you migrate the server?
Scott PletcherSenior DBA
Most Valuable Expert 2018
Top Expert 2014
Commented:
??  Presumably if you're storing dates as strings in a local table, they will be stored in the local format.

If you're entering dates yourself as literals, you should always use format:
'YYYYMMDD hh:mm:ss' --hh=24hr
which works with any settings so you don't need a format code.

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial