Formatting Datetime2 in SQL Server - sql

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.

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,':'))

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

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

How to convert date time format in SQL Server like '2017-03-04 10:07:03.490' to date format which is seperated by - like '2-11-2016'

I am tying to make date comparison with the query
select *
from dbo.OH_Case
where dbo.OH_Case.CreatedDate between Convert(varchar(30),'24/04/2017', 102)
and Convert(varchar(30),'01/05/2017', 102)
but it throws this error:
Msg 242, Level 16, State 3, Line 1
The conversion of a varchar data type to a datetime data type resulted in an out-of-range value.
My application passes data in '01/05/2017' format and the date information in SQL Server is stored in '2017-03-04 10:07:03.490' format. What should I do to make both of these in same format which allows comparison?
First, you're converting a string literal to a varchar. Convert it to a datetime instead.
Second, you're passing in 24/04/2017, but date format 102 is yyyy.mm.dd. Try date format 103 for dd/mm/yyyy:
convert(datetime, '24/04/2017', 103)
Here dbo.OH_Case.CreatedDate is of data type Datetime and you have to convert your values in Datetime format for filter.
convert columns in Datetime format and format will be same for all. In your case, convert values in Datetime instead of Varchar and it will work fine.
select * from
dbo.OH_Case
where dbo.OH_Case.CreatedDate between cast('24/04/2017' as datetime) and
cast('01/05/2017' as datetime)
Updates:
Siddharth, I have checked you date values and figured out that issue is in date "24/04/2017". This format is for "MM/dd/yyyy". and 24 is passed as month which is not valid. Therefore it is throwing exception. I have updated result
to handle such exceptions.
select * from
dbo.OH_Case
where dbo.OH_Case.CreatedDate between convert(datetime, '24/04/2017', 103) and
convert(datetime, '01/05/2017', 103)
Here dbo.OH_Case.CreatedDate is of data type Datetime and you have to convert your values in Datetime format for filter. convert columns in Datetime format and format will be same for all. In your case, convert values in Datetime instead of Varchar and it will work fine.
select * from dbo.OH_Case format(where dbo.OH_Case.CreatedDate, 'dd/mm/yyyy') as CreatedDate

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).

Convert dd/mm/yy string to yyyy-mm-dd

I am having issues converting a string in dd/mm/yy hh:mi:ss format to yyyy-mm-dd hh:mi:ss format.
I have tried using CONVERT() as follows:
select CONVERT(VARCHAR, '11/10/11 10:56:58', 120)
But that returns no change:
11/10/11 10:56:58
You need to convert to datetime first to change a string to reflect a certain regional format. Be sure you are interpreting the datetime value correctly, too; on some systems, that will be October 11th, on others it will be November 10th.
SELECT CONVERT(CHAR(19), CONVERT(DATETIME, '11/10/11 10:56:58', 3), 120);
Finally, use the correct number of characters in your char or varchar declarations. Not specifying a length is lazy and can lead to problems. See:
Bad habits to kick : declaring VARCHAR without (length)
This will work:
SELECT CONVERT(VARCHAR(19),CONVERT(DATETIME,'11/10/11 10:56:58',3),120)
The issue: you are converting a VARCHAR to a VARCHAR.
Your query is fine if you use a DATETIME.
SELECT CONVERT(VARCHAR(19), CAST('11/10/11 10:56:58' AS DATETIME), 120);
See fiddle.