2012-01-22 53 views
-1

我從數據庫中取兩個值作爲字符串。現在我想減去這兩個值。請幫助我,並提前致謝。如何在C#中減去時間

private void button3_Click_1(object sender, EventArgs e) 
    { 
     label4.Visible = true; 
     textBox3.Visible = true; 
     string condur = Properties.Settings.Default.DBConnectionString; 
     SqlConnection connection = new SqlConnection(condur); 
     string q1 = "select in_time from in_time where car_reg='" + comboBox1.Text + "' "; 

     string q2 = "select out_time from out_time where car_reg='" + comboBox1.Text + "' "; 
     SqlCommand command1 = new SqlCommand(q1, connection); 
     SqlCommand command2 = new SqlCommand(q2, connection); 
     try 
     { 
      connection.Open(); 
      string q3=command1.ExecuteNonQuery().ToString(); 

      string q4=command2.ExecuteNonQuery().ToString(); 



      DateTime dt1 = DateTime.Parse(q3); 
      DateTime dt2 = DateTime.Parse(q4); 
      TimeSpan result = dt2 - dt1; ; 
      string result1 = result.ToString(); 
      textBox3.Text = result1; 

      //MessageBox.Show("Insertion successful!"); 
      //textBox1.Text = ""; textBox2.Text = ""; textBox3.Text = ""; comboBox1.Text = ""; comboBox3.Text = ""; textBox11.Text = ""; textBox6.Text = ""; textBox8.Text = ""; textBox9.Text = ""; richTextBox1.Text = ""; textBox4.Text=""; 
     } 
     catch (Exception exp) 
     { 
      throw exp; 
     } 
     finally 
     { 
      connection.Close(); 
     } 

    } 
+1

什麼問題?您顯示的代碼將成功減去這些值。 – JaredPar

+6

好吧,那什麼都行不通,結果如何,你是否會得到例外,總的來說 - 問題是什麼? – neeKo

+0

是q3和q4有效數據嗎?告訴我們你得到了什麼以及你的期望。 –

回答

4

看起來你回答了自己的問題:

TimeSpan result = dt2 - dt1; 

在C#中減去兩個DateTime值,只需使用減法運算符。如果您發佈的代碼示例出現問題,您應該描述錯誤以及您期望發生的事情。

編輯迴應評論

該異常無關,與減去的日期,它是與轉換從類型的類型日期時間。您正在試圖解析從字符串到日期時間:

DateTime dt1 = DateTime.Parse(q3); 

失敗的原因是q3並不代表一個有效的字符串。之所以說,是你(don't)查詢方式:

string q3=command1.ExecuteNonQuery().ToString(); 

ExecuteNonQuery不返回查詢的結果,而是返回更改的行數。換句話說,ExecuteNonQuery不適用於查詢,但用於更新場景等。

您可能想要的是使用ExecuteScalar,它將從查詢中返回單個值。如果數據庫中的類型正確,它將作爲DateTime返回,因此您不需要執行DateTime.Parse部分。你的代碼的相關部分將變成:

DateTime q3 = (DateTime)command1.ExecuteScalar(); 
DateTime q4 = (DateTime)command2.ExecuteScalar(); 

TimeSpan result = q4-q3; 

哦,順便說一句,請看看在谷歌的術語「SQL注入」和「參數化查詢」。

+0

「字符串未被識別爲有效的日期時間。」這個例外消息顯示 – AsifAbdullah

+0

我說的是入門時間和員工的退出時間和存儲在一個數據庫的兩個不同表中的tgem。現在我想減去存儲在特定employee.bt數據庫中的兩個值。每次出現異常時,我無法解決它。 anu one幫我在case.its緊急....... – AsifAbdullah

+0

請看我更新的答案。如果您首先包含該信息,那麼在幾分鐘內您就能得到答案。不要期望人們在這裏運行和調試你的代碼。詢問時請包括所有相關信息。 – driis