Converting XML date (ISO 8061) to Datetime in SQL Server - sql

I have an XML column, that I'm extracting the datetime from:
SELECT PaymentXml.query('data(/PaymentSummary/SubmittedDate)') as 'ISO 8061 format'
But I want to get it into DateTime that I can work with in SQL Server.
Directly converting to datetime doesn't work
,convert(datetime,PaymentXml.query('data(/PaymentSummary/SubmittedDate)')) as 'VarChar Format'
Explicit conversion from data type xml to datetime is not allowed.
I can convert it to varchar
convert(varchar(150),PaymentXml.query('data(/PaymentSummary/SubmittedDate)')) as 'VarChar Format'
But can't get that result to datetime.
,convert(datetime,convert(varchar(150),PaymentXml.query('data(/PaymentSummary/SubmittedDate)'))) as 'DateTime Format'
Conversion failed when converting date and/or time from character string.
Obviously I'm been working with XML in SQL Server for all of 30 minutes / don't really know what I'm doing.

Instead of datetime try datetime2 or datetimeoffset. ISO 8601 datetime precision exceeds the regular SQL Server datetime column type.

Firstly, you should use .value to get a single XML value, not .query.
You can use CONVERT(datetime2 with style 127 to convert ISO-8061 dates:
SELECT
CONVERT(datetime2,
PaymentXml.value('(/PaymentSummary/SubmittedDate/text())[1]','varchar(30)'),
127) AS 'ISO 8061 format'
FROM YourTable
db<>fiddle

Related

How to convert YYMMDDhhmm formatted NVARCHAR into YYYY-MM-DD hh:mm:ss formatted DATETIME?

For example:
The value 2208111603(nvarchar) needs to be converted to 2022-08-11 00:00:00(datetime).
The things I have tried and the corresponding errors I've got so far as follow:
CAST(DATE_TIME AS numeric) works but CAST(CAST(DATE_TIME AS numeric) AS datetime) returns Arithmetic Overflow Error.
convert(datetime2, CAST(DATE_TIME AS numeric), 105) returns
Explicit conversion from data type numeric to datetime2 is not allowed
CONVERT(datetime2, DATE_TIME , 105) returns
Conversion failed when converting date and/or time from character
string.
CONVERT(datetime2, CONVERT(CHAR(10), DATE_TIME), 105) returns
Conversion failed when converting date and/or time from character
string.
Finally, I tried PARSE(DATE_TIME AS date USING 'en-US') which resulted in
Error converting string value '2208111603' into data type date using
culture 'en-US'.
The SQL Server's CONVERT function also has some built-in formats as a third parameter for converting varchar to datetime. So, I tried SELECT convert(datetime,'2208111603',112) which resulted in the same error (Msg 241):
Conversion failed when converting date and/or time from character
string.
Any help would be much appreciated!
With just a bit of string manipulation...
Note: this will assume century of 20
Example
Declare #S varchar(50) ='2208111603'
Select try_convert(datetime,stuff(stuff(#S,7,0,' '),10,0,':'))
Results
2022-08-11 16:03:00.000
A little bit ugly, but to overcome the century indicator you an nest a little logic to conditionally add 19.
Declare #S varchar(50) ='6408111603'
Select try_convert(datetime,case when left(#S,2)>'50' then '19' else '' end + stuff(stuff(#S,7,0,' '),10,0,':'))

Formatting Datetime2 in SQL Server

I am trying to format a datetime2 into yyyy-mm-dd hh:mm:ss format.
I have tried the below options:
This is throwing an error:
SELECT CONVERT(datetime2, 120);
This works fine, but I need the output of type datetime2
SELECT CONVERT(VARCHAR(19), GETDATE(), 120);
How can I achieve this?
You are calling the CONVERT() function without specifying the data type to convert to, so in your case SELECT CONVERT(datetime2, 120); SQL Server will try to convert the value 120 to a datetime2 and that's why you get this error (which you don't provide)
Explicit conversion from data type int to datetime2 is not allowed.
To use CONVERT() with date and time styles, you need to pass
CONVERT(<datatype to convert to>, <Value to be converted>, <Style>).
The SYSUTCDATETIME returns a datetime2 you can convert to as
SELECT CONVERT(VARCHAR(20), SYSUTCDATETIME(), 120)
--Change SYSUTCDATETIME() with your column/variable
For what you say
but I need the output of type datetime2
A DATETIME doesn't have a format, it's a binary value, thus you need to convert it to a formatted string. Since you need to return a DATETIME2 then you need to leave it as it is, and do the formatting in presentation layer.

Why does SQL Server convert VARCHAR to DATETIME using an invalid style?

I can't make out from the documentation why SQL Server parses a text in a format other than the specified style.
Regardless of whether I provide text in the expected format:
SELECT CONVERT(DATETIME, N'20150601', 112)
or incorrect format (for style 113):
SELECT CONVERT(DATETIME, N'20150601', 113)
The results are the same: 2015-06-01 00:00:00.000 I would expect the latter to fail to convert the date (correctly).
What rules does it employ when trying to convert a VARCHAR to DATETIME? I.e. why does the latter (incorrect format style) still correctly parse the date?
EDIT: It seems I've not been clear enough. Style 113 should expect dd mon yyyy hh:mi:ss:mmm(24h) but it happily converts values in the format yyyymmdd for some reason.
Because the date is in a canonical format ie(20150101). The database engine falls over it implicitly. This is a compatibility feature.
If you swapped these around to UK or US date formats, you would receive conversion errors, because they cannot be implicitly converted.
EDIT: You could actually tell it to convert it to a pig, and it would still implicitly convert it to date time:
select convert(datetime,'20150425',99999999)
select convert(datetime,'20150425',100)
select convert(datetime,'20150425',113)
select convert(datetime,'20150425',010)
select convert(datetime,'20150425',8008135)
select convert(datetime,'20150425',000)
And proof of concept that this is a compatibility feature:
select convert(datetime2,'20150425',99999999)
Although you can still implicitly convert datetime2 objects, but the style must be in the scope of the conversion chart.
Reason why is the date N'20150601' converted to valid datetime is because of fact that literal N'20150601' is universal notation of datetime in SQL Server. That means, if you state datetime value in format N'yyyymmdd', SQL Server know that it is universal datetime format and know how to read it, in which order.
You should convert to varchar type in order to apply those formats:
SELECT CONVERT(varchar(100), CAST('20150601' as date), 113)
OK, you are converting datetime to datetime. What did you expect? In order to apply formats you should convert to varchar and you have to have date or time type as second parameter.

Sql query for CONVERT datetime to a different datetime Format in SQL 2005?

My datetime column is in MM/dd/yyy format. i want this to be converted in dd/MM/yyyy, I am able to converting this datetime to narchar.
select convert(nvarchar,columnname,103) from dbo.table
i m getting my answer like "dd/MM/yyyy" but it is string. if i write datetime in place of nvarchar
i am getting "yyyy-MM-dd" whaa is the query for getting "dd/MM/yyyy"
http://msdn.microsoft.com/en-us/library/ms187928.aspx
check out
see Microsoft's explanation on date formats
the one you're looking for is 20 or 120
BTW, you should supply with varchar with a number like this varchar(10)

Convert varchar which represents DateTime in universal format (dd/MM/yy hh:mm) to DateTime

I have a table with a varchar column which represent date and time in the next format:
dd/MM/yy hh:mm
For example: 27/01/13 07:57
I need to convert this column to DateTime type.
I tried to do it without success.
Assume that #varcharDT contains the VarChar DateTime and I want insert the converted value to #dateTimeDT variable.
DECLARE #varcharDT varchar(1000)
SELECT #varcharDT = dateTimeColumn from dbo.tempTable
--Trying to convert
DECLARE #dateTimeDT DateTime
SET #dateTimeDT= CONVERT (DATETIME, #varcharDT )
The last line raise the next exception:
Conversion failed when converting date and/or time from character string.
I think the conversion fails because my VarChar DateTime is in custom format.
How can I solve it?
I am working with SQL Server 2008 R2
Thanks
Try:
CONVERT(datetime, #varcharDT, 3)
The last number is the style for the convert. The list can be found in the MSDN documentation article CAST and CONVERT (Transact-SQL).