1

This seems like it should be really obvious, but how can I put a DateTime object into an MSSQL database? When I convert it to a string, it keeps adding "-7:00" at the end for the time zone offset and so the query isn't accepted. How can I fix this?

2 Answers 2

1

How are you trying to insert the DateTime into the database? If you're converting it to a string to be passed into a stored procedure (bad idea; better to use the date SQL type), then you should first convert all DateTime objects to UTC using the .net method ToUniversalTime. Once in UTC, the DateTime will have no timezone offset.

Sign up to request clarification or add additional context in comments.

2 Comments

Hm... maybe that's not it then. This is what I get after using ToUniversalTime: '2011-05-28T22:33:52.0549471Z'. That's the correct time but it's still not accepted as a datetime.
Ah, nevermind - apparently it only allows 3 digits of precision. Thanks. +1
1

Assuming you are using C#, I would suggest the following:

SqlCommand cmd = new SqlCommand("INSERT INTO yourTable (dateTimeColumn) VALUES (@value)", connection);
cmd.Parameters.AddWithValue("@value", yourDateTimeObject);

cmd.ExecuteNonQuery();

This will work for inserting the value. If not, please post your code to show where the error is because that means that the datetime object you are getting your value from is passing in the data wrong.

4 Comments

I can't use parameters in this case.
Doing inline would work the same way basically. Just look at your output of ToString() to ensure it is giving you want you want. If you want to change it, either to a different "To" statement or format the string the way you want it (or the database is expecting it).
@minitech Why can't you use parameters?
@Neil: I'm building a library to properly format the strings.

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.