Need help converting datetime from yyyy-dd-mm hh:mm:ss.sss to yyyy-mm-dd hh:mm:ss.sss

Is it possible to convert datetime value from yyyy-dd-mm hh:mm:ss.sss to yyyy-mm-dd hh:mm:ss.sss?

I have inserted datetime records into sql table, with incorrect datetime format for some values.

I need to correct the datetime values  for the below results if possible.

from
2015-01-08 09:11:56.000
2015-01-08 09:44:04.000
2015-01-08 09:53:21.000
2015-01-08 12:27:42.000
2015-01-08 13:15:43.000
2015-02-08 08:49:48.000
2015-03-08 11:27:50.000
2015-04-08 09:57:15.000

To
2015-08-01 09:11:56.000
2015-08-01 09:44:04.000
2015-08-01 09:53:21.000
2015-08-01 12:27:42.000
2015-08-01 13:15:43.000
2015-08-02 08:49:48.000
2015-08-03 11:27:50.000
2015-08-04 09:57:15.000

I appreciate any help.

Thanks in advance.

September 6th, 2015 12:07pm

A datetime value is stored in the database as a binary value that has no formatting.  To fix the incorrect values where the month and day values are reversed, you need to swap the month and day components of the datetime value.  One method is to convert the bad datetime values to a ISO 8601 string with the month/day components swapped, and then parse back into datetime value.

In SQL 2014, you can use the FORMAT function:

UPDATE dbo.YourTable
SET DateTimeColumn = CAST(FORMAT(DateTimeColumn, 'yyyy-dd-MMTHH:mm:ss.fff') AS datetime)
WHERE <your criteria to identify wrong dates>

In earlier SQL versions:

UPDATE dbo.YourTable
SET DateTimeColumn = CAST(LEFT(CONVERT(varchar(23), DateTimeColumn, 121), 4)
		  + SUBSTRING(CONVERT(varchar(23), DateTimeColumn, 121), 8, 3)
		  + SUBSTRING(CONVERT(varchar(23), DateTimeColumn, 121), 5, 3)
		  + 'T'
		  + SUBSTRING(CONVERT(varchar(23), DateTimeColumn, 121), 12, 12)
		  AS datetime)
WHERE <your criteria to identify wrong dates>

Free Windows Admin Tool Kit Click here and download it now
September 6th, 2015 1:01pm

Thank you
September 6th, 2015 1:23pm

This topic is archived. No further replies will be accepted.

Other recent topics Other recent topics