Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

SQL Server – Cast specific string date format to date datatype

I am trying to insert data into a DATE column in Microsoft SQL using the code below:

INSERT INTO sde.AMD_NDVI_CAT (OBJECTID, Name, ImageDate) 
VALUES (6199,'VI_{960D55A4-EEFD-45DD-80FD-81B5113C43D5}_20220122T090159', CAST('20220122T090159' AS DATE))

What I get is:

Conversion failed when converting date and/or time from character string.

The data to be inserted into ImageDate column has the format YYYYMMDDTHHMMSS. I did not find this format on the Microsoft webpage (https://docs.microsoft.com/en-us/sql/t-sql/functions/cast-and-convert-transact-sql?view=sql-server-ver15). How can I convert it to date in order to be inserted into the table?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Thanks!

>Solution :

Since date suggests you don’t care about time:

SELECT CONVERT(date, LEFT('20220122T090159', 8));

If you need time too, it gets quite ugly.

DECLARE @funny_string char(15) = '20220122T090159';

SELECT TRY_CONVERT(datetime, 
  LEFT(@funny_string, 8) + ' ' 
  + STUFF(STUFF(RIGHT(@funny_string, 6), 3, 0, ':'),6, 0, ':'));
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading