简体   繁体   中英

Formatting SQL friendly Date/Times in C#

I am building some test scenarios for my application. In order to do this, I have some code that is generating some SQL to help me test properly. A sample of the SQL that is generated is shown here:

INSERT INTO MyTable
(
 [ID],
 [Name],
 [CheckInDate],
 [CheckOutDate]
)
VALUES
(
  1,
  'A title',
  'Sat, 17 Dec 2011 14:33:12 GMT',
  'Sat, 17 Dec 2011 15:13:12 GMT'
)

When I attempt to execute this SQL, I receive the following: Conversion failed when converting date and/or time from character string.

How can i format the date/time strings so that SQL Server 2008 will accept them? I really need my C# code to generate the SQL (including the date/time items) to create my tests properly.

Thank you!

The way to solve this is to use the ISO-8601 date format that is supported by SQL Server - this format works always - regardless of your SQL Server language and dateformat settings.

The ISO-8601 format is supported by SQL Server comes in two flavors:

  • YYYYMMDD for just dates (no time portion) - note here: no dashes! , that's very important! YYYY-MM-DD is NOT independent of the dateformat settings in your SQL Server and will NOT work in all situations!

or:

  • YYYY-MM-DDTHH:MM:SS for dates and times - note here: this format has dashes.

This is valid for SQL Server 2000 and newer.

If you use SQL Server 2008 and the DATE datatype (only DATE - not DATETIME !), then you can indeed also use the YYYY-MM-DD format and that will work, too, with any settings in your SQL Server.

Don't ask me why this whole topic is so tricky and somewhat confusing - that's just the way it is. But with the YYYYMMDD format, you should be fine for any version of SQL Server and for any language and dateformat setting in your SQL Server.

You can use SqlParameters .

So your command would be:

INSERT INTO MyTable
(
 [ID],
 [Name],
 [CheckInDate],
 [CheckOutDate]
)
VALUES
(
  1,
  'A title',
  @CheckInDate,
  @CheckOutDate
)

And you'd insert the dates like so:

SqlParameter checkin = new SqlParameter("@CheckInDate", SqlDbType.DateTime);
SqlParameter checkout = new SqlParameter("@CheckOutDate", SqlDbType.DateTime);

checkin.Value = DateTime.Today; // Format these to the desired dates
checkout.Value = DateTime.Today;

command.Parameters.Add(checkin);
command.Parameters.Add(checkout);

更好的方法是根本不格式化日期,参数化insert语句,并将日期作为命令参数传递。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM