2011-12-07 43 views
1

我正在使用SQL Server 2008和我的字段有DATE類型,但在Visual Studio中我的程序時,當我讀取可能的數據它顯示我DATE & TIME我該怎麼辦?我試圖在SELECT中查詢我的程序,但它給了我一些錯誤,我該如何解決這個問題?SQL Server 2008日期類型showes我日期和時間在visual studio

這是我的後臺代碼:

 protected void Page_Load(object sender, EventArgs e) 
     { 
       SqlCommand cmd = new SqlCommand(); 
       cmd.Connection = new SqlConnection(Class1.CnnStr); 
       SqlDataReader reader; 


       cmd.CommandText = "select ContractStartDate,MandateValidDate from table where [email protected]"; 
       cmd.Connection.Open(); 
       cmd.Parameters.AddWithValue("@BrokerName", BrokerName_txt.Text); 
       reader = cmd.ExecuteReader(); 

       if (reader.Read()) 
       { 


        ContractStartDate_txt.Text = Convert.ToDateTime(reader["ContractStartDate"]).ToString("dd/MM/yyyy"); 
        MandateValidDate_txt.Text = Convert.ToDateTime(reader["MandateValidDate"]).ToString("dd/MM/yyyy");    
        reader.Close(); 
       } 
       cmd.Connection.Close(); 

      } 

因爲我想保存數據後閱讀它給我的錯誤:

Conversion failed when converting date and/or time from character string.

+0

因爲你有'DateTime',你可以選擇只使用日期時間實例 – V4Vendetta

回答

4

您使用Convert.ToDateTime()從數據庫返回的字符串轉換首先,稍後通過使用DateTime.ToString("dd/MM/yyyy"),您可以從Date &時間僅獲取Date值。

ContractStartDate_txt.Text = Convert.ToDateTime(reader["ContractStartDate"]).ToString("dd/MM/yyyy"); 
MandateValidDate_txt.Text = Convert.ToDateTime(reader["MandateValidDate"]).ToString("dd/MM/yyyy"); 
+1

上的'.Date'屬性或'ToString(「dd/MM/YYYY」)'加入你的答案,你也可以做Convert.ToDateTime(reader [「ContractStartDate」])。ToShortDateString(); – mehul9595

+0

@ mehul9595我的同事在某些代碼中使用了這種方法,當我們在具有不同CurrentCulture設置的計算機上運行它們時,會導致大量測試中斷。這不是一個好主意。 – phoog

+0

@phoog:在這種情況下使用DateTime.Parse()方法將是一個很好的解決方案。例如:DateTime.Parse(reader [「ContractStartDate」],CultureInfo.CurrentUICulture).ToShortDateString(); – mehul9595

0

你有一個鑄造的問題,需要轉換爲正確的排序規則爲DB

即分貝可能要01/23/2011美國格式,你必須23/01/2011作爲英國/澳大利亞格式

您可以修復在代碼或數據庫給你..

一個string.format("dd/mmm/yyyy");作爲參數

CONVERT(CHAR, @adate,103) 

我們總是傳遞26Feb2011串到DB這樣,我們繞過整理髮布

0

日期類型通常映射到DateTime類型(有表示午夜的時間成分)。使用接受格式參數的ToString重載(例如,someDate.ToString(「yyyy-MM-dd」)

使用ISO年份優先格式可以避免日/月/年/而不依賴於使用月份名稱的文字

相關問題