MsWiggles
MsWiggles

Reputation: 33

SQL Server : Convert from VARCHAR to DATETIME

Current Date Format: 12-18-2018-03:14:48

I want to convert to: 2018-12-18 03:14

Currently using SQL Server 2008

I'm using this code syntax:

DECLARE @input VARCHAR(35) = '12-18-2018-03:14:48'

SELECT CONVERT(DATETIME, @input, 120)

Error:

The conversion of a varchar data type to a datetime data type resulted in an out-of-range value

Please help. Thank you!

Upvotes: 1

Views: 115

Answers (1)

Tim Biegeleisen
Tim Biegeleisen

Reputation: 520928

I'm not sure that your current datetime literal falls into any mask which SQL Server can recognize. But we can try using TRY_CONVERT here, replacing the middle dash with a space:

SELECT TRY_CONVERT(datetime, STUFF(@input, 11, 1, ' ')) AS output;

18/12/2018 03:14:48

Demo

Edit:

If you are using an earlier version of SQL Server which does not support TRY_CONVERT, then we can try explicitly using CONVERT:

SELECT CONVERT(datetime, STUFF(@input, 11, 1, ' ')) AS output;

Upvotes: 1

Related Questions