0

I have below string of date time

2017-09-06 00:36:32.473491+05:30

I want to store this date time into MS SQL Server table and my datatype for this column is datetime.

I tried CAST but it gives me the following error Conversion failed when converting date and/or time from character string. So please help me to fix this. I am using MS SQL Server 2014

2
  • How do you import it? Maybe you should parse it there to DateTime. In C# f.e. it's easy: DateTime.Parse("2017-09-06 00:36:32.473491+05:30") works as it is. Commented Oct 24, 2017 at 13:49
  • @TimSchmelter I am not using any programming language. I try select CAST('2017-09-06 00:36:32.473491+05:30' AS DateTime) as date_time; in MS SQL Server itself. Commented Oct 24, 2017 at 13:57

3 Answers 3

1

Here is a super easy alternative...

SELECT CAST(left('2017-09-06 00:36:32.473491+05:30',19) as datetime)
Sign up to request clarification or add additional context in comments.

Comments

1

You need to strip out the milliseconds and time offset before you can CAST to DATETIME.

DECLARE @s NVARCHAR(100) = '2017-09-06 00:36:32.473491+05:30'
SELECT CONVERT(NVARCHAR(19), @s, 121)
SELECT CAST(CONVERT(NVARCHAR(19), @s, 121) AS DATETIME)

However, if your datatype was DATETIME2 then you wouldn't need to

DECLARE @s NVARCHAR(100) = '2017-09-06 00:36:32.473491+05:30' SELECT
CONVERT(NVARCHAR(25), @s, 121) SELECT CAST(CONVERT(NVARCHAR(25), @s,
121) AS DATETIME2)

Comments

0

try this CONVERT(DATETIME,'2017-09-06 00:36:32.473') do the job but not with your precision!

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.