简体   繁体   中英

How to convert datetime in c# so it works with sql server?

If i write the following query in sql it works fine, but if i run it from my c# program it fails. I get a -1 value as the result of the query. I think it has something to do with the conversion. It supposed to be a third textbox in the program and in it the result of the query (the result should be displayed in the third textbox). Here is the code:

 conn.Open();
            string anfrage = "select sum(Rechnungsbetrag)  from tbl_Rechnung where AusDatum between '"+txtbox1.Text+"' and '"+txtbox2.Text+"'"; 
            SqlCommand comm = new SqlCommand(anfrage, conn);
            comm.ExecuteNonQuery();

Format your date in ISO8601 format: YYYY-MM-DDThh:mm:ss.nnn[ Z ]

Here's how you do this in C#: http://msdn.microsoft.com/en-us/library/az4se3k1(v=vs.110).aspx#Roundtrip

There are a couple of things wrong. First, txtbox1.text and txtbox2.text are strings. You have to convert them to DateTime objects.

Next, you really want to use query parameters for a variety of reasons.

Finally, with date range queries, the between keyword can cause you to miss records. It's safer to do this sort of thing:

where SomeDateField >= @StartDate
and SomeDateField < the day after @EndDate
 string anfrage = "select sum(Rechnungsbetrag)  from tbl_Rechnung where AusDatum between Convert(varchar(10),'"+txtbox1.Text+"',102) and Convert(varchar(10),'"+txtbox2.Text+"',102)";

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