2014-02-23 37 views
1

我使用ASP.NET從數據庫加載數據以顯示購買的物品的日期,但它也在其旁邊顯示12:00:00 AM的時間戳。投射字符串日期作爲日期

如何打印該值才能顯示日期?

private void UpdateInventory(int index) 
{ 
    DataView inventoryTable = (DataView)SqlDataSource1.Select(DataSourceSelectArguments.Empty); 
    DataRowView row = (DataRowView)inventoryTable[index]; 

    currentInventory.fac_ID = row["fac_ID"].ToString(); 
    currentInventory.inv_Quantity = row["inv_Quantity"].ToString(); 
    currentInventory.inv_Purchase_Date = row["inv_Purchase_Date"].ToString(); 

    lblFacilityID.Text = currentInventory.fac_ID; 
    lblQuantity.Text = currentInventory.inv_Quantity; 
    lblPurchaseDate.Text = currentInventory.inv_Purchase_Date; 
} 

protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e) 
{ 
    UpdateInventory(DropDownList1.SelectedIndex); 
} 

public string fac_ID { get; set; } 
public string inv_Quantity { get; set; } 
public string inv_Purchase_Date { get; set; } 

回答

4

如果你不需要什麼太特別的,只是想省略的時候,你可以這樣做:

lblPurchaseDate.Text 
    = Convert.ToDateTime(row["inv_Purchase_Date"]).ToShortDateString(); 

這將顯示類似:

2/22/2014 
1

您可以使用ToShortDateString方法:

currentInventory.inv_Purchase_Date = (row["inv_Quantity"] as DateTime).ToShortDateString(); 

或者使用傳遞一個字符串參數specify a format

currentInventory.inv_Purchase_Date = (row["inv_Quantity"] as DateTime).ToString("d MMMM YYYY"); 
0

你可以使用DateTime.ToString(string) - 例如:

currentInventory.inv_Purchase_Date = 
    Convert.ToDateTime(row["inv_Purchase_Date"]).ToString("d"); 

對於string參數,你可以使用"d",這將產生相同的結果DateTime.ToShortDateString()as MSDN explains;但您也可以靈活地使用其他standardcustom短日期格式字符串。

請注意,如果你的代碼不能承擔的文化,你應該考慮轉換選項/重載槓桿IFormatProvider - 例如:

var ci = new CultureInfo("en-US"); // or "ja-JP" etcetera 

// ... 

currentInventory.inv_Purchase_Date = 
    DateTime.Parse(row["inv_Purchase_Date"].ToString(), ci).ToString("d", ci);