2013-10-02 133 views
1

當讀取SQl日期時間字段時,只有我可以將日期與時間..如何從Ajax或某種方法只獲取日期文本框。將SQL日期時間格式轉換爲字符串

這就是我需要做的

http://i.stack.imgur.com/n0fgG.jpg

這就是我如何之日起,到文本框。

protected void ddlBatch_SelectedIndexChanged(object sender, EventArgs e) 
    { 
     String strConnString = ConfigurationManager.ConnectionStrings["CBConnectionString"].ConnectionString; 
     const String strQuery = "select ItemIdentityCode, Qty, PurchasingPrice, ExpireDate, DiscountRate, IssueMode, Principle, Force from DEL_PurchasesLines where BatchNumber = @BatchNumber"; 
     SqlConnection conPR = new SqlConnection(strConnString); 
     SqlCommand cmdPR = new SqlCommand(); 
     cmdPR.Parameters.AddWithValue("@BatchNumber", ddlBatch.SelectedItem.Value); 
     cmdPR.CommandType = CommandType.Text; 
     cmdPR.CommandText = strQuery; 
     cmdPR.Connection = conPR; 
     try 
     { 
      conPR.Open(); 
      SqlDataReader sdr = cmdPR.ExecuteReader(); 
      while (sdr.Read()) 
      { 

       tHFExpiaryDate.Text = sdr["ExpireDate"].ToString(); 

      } 
     } 
     catch (Exception ex) 
     { 
      //throw ex; 
     } 

     finally 
     { 
      conPR.Close(); 
      conPR.Dispose(); 
     } 
    } 

回答

8

不要原始值轉換爲string擺在首位 - 這應該已經是DateTime :

DateTime date = (DateTime) dsr["ExpireDate"]; 

然後,你可以把它轉換成任何格式你感興趣的:

// TODO: Consider specifying the culture too, or specify a standard pattern. 
tHFExpiaryDate.Text = date.ToString("MM/d/yyyy"); 

它分開的問題是很重要的:「我怎樣才能從數據庫中的數據以適當的類型?」從「我應該如何向用戶呈現數據?」

+0

只是我看到的格式應該是「M/d/yyyy」(2013年10月2日,如圖中所示)的旁註。 –

+0

@ AlessandroD'Andria:固定,謝謝。 –

+0

謝謝@Jon Skeet它正在很好地工作...... :) –

1

試着這麼做:

DateTime.ParseExact(sdr["ExpireDate"].ToString(), "MM/d/yyyy", CultureInfo.InvariantCulture) 

在您的樣本:

tHFExpiaryDate.Text = DateTime.ParseExact(((DateTime)dt.Rows[0][0]).ToString("MM/d/yyyy"), "MM/d/yyyy", System.Globalization.CultureInfo.CurrentCulture).ToString("MM/d/yyyy")); 
+0

如何使用這個答案在我的情況..你可以解釋請參見 –

+0

我編輯..... – Sadique

+0

'SDR [「ExpireDate」]將是對象的類型。假設你的數據存儲有效的信息,我們將其轉換爲字符串,並解析它 - 最後我們提供一個格式(比如第一個月)。 – Sadique

0

這總是對我的作品

protected String getDate(string date) 
{ 
    DateTime dDate; 
    string sdate = null; 
    if (!string.IsNullOrEmpty(date.ToString())) 
    { 
     dDate = DateTime.Parse(date.ToString()); 
     sdate = dDate.ToString("dd/MM/yyyy"); 
     sdate = dDate.ToLongDateString(); 
    } 
    return sdate; 
} 

其他日期格式例如http://www.dotnetperls.com/datetime-format

+0

謝謝@KnowledgeSeeker真正有用的一點,,,包括鏈接.. :) –

相關問題