mocode10
mocode10

Reputation: 598

SQL Server Convert String to Date

I am having an issue converting 2PM to a date.

This code fails:

SELECT CONVERT(datetime, '2018/10/23 14:00:00')

with this error:

Msg 241, Level 16, State 1, Line 2
Conversion failed when converting date and/or time from character string.

However, this code:

SELECT CONVERT(datetime, '2018/10/23 09:55:03')

works fine.

Why?

Upvotes: 1

Views: 635

Answers (1)

marc_s
marc_s

Reputation: 755321

DATETIME in SQL Server has a tendency to be extremely picky about what string format can be converted into it. The best way to solve this is to use the (slightly adapted) ISO-8601 date format that is supported by SQL Server - this format works always - regardless of your SQL Server language and dateformat settings.

The ISO-8601 format is supported by SQL Server comes in two flavors:

  • YYYYMMDD for just dates (no time portion); note here: no dashes!, that's very important! YYYY-MM-DD is NOT independent of the dateformat settings in your SQL Server and will NOT work in all situations!

or:

  • YYYY-MM-DDTHH:MM:SS for dates and times - note here: this format has dashes (but they can be omitted), and a fixed T as delimiter between the date and time portion of your DATETIME.

This is valid for SQL Server 2000 and newer.

So try these statements:

SELECT CONVERT(DATETIME, '2018-10-23T14:00:00')
SELECT CONVERT(DATETIME, '2018-10-23T09:55:03')

do they both work?

Or if you use SQL Server 2008 or newer, make use of the new DATE datatype (only DATE - not DATETIME!); then you can indeed also use the YYYY-MM-DD format and that will work, too, with any settings in your SQL Server.

Don't ask me why this whole topic is so tricky and somewhat confusing - that's just the way it is. But with the YYYYMMDD format, you should be fine for any version of SQL Server and for any language and dateformat setting in your SQL Server.

The recommendation for SQL Server 2008 and newer is to use DATE if you only need the date portion, and DATETIME2(n) when you need both date and time. You should try to start phasing out the DATETIME datatype if ever possible

Upvotes: 1

Related Questions