2014-02-23 41 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);