2010-11-04 208 views

回答

75
var day = value.Date; // a DateTime that will just be whole days 
var time = value.TimeOfDay; // a TimeSpan that is the duration into the day 
+1

没想到它是如此明显! :) – gideon 2012-02-01 13:25:28

23

您还可以使用DateTime.Now.ToString("yyyy-MM-dd")的日期,并DateTime.Now.ToString("hh:mm:ss")的时间。

+2

只有当你想要一个字符串... – Dismissile 2010-11-04 13:40:03

+0

良好的通话。这就是我匆忙回答的原因。马克Gravell钉牢它。 – 2010-11-04 14:24:07

+2

我想说,你正在寻找一个经常足以让这个答案有价值的字符串。 – GWLlosa 2010-11-04 15:08:12

13

您可以使用Instance.ToShortDateString()的日期,
Instance.ToShortTimeString()的时间从同一个实例获得的日期和时间。

-1

有时你想拥有你的GridView一样简单:

<asp:GridView ID="grid" runat="server" /> 

你不想指定任何绑定列,你只是想你的网格DataReader的结合。 下面的代码帮助我在这种情况下格式化DateTime。

protected void Page_Load(object sender, EventArgs e) 
{ 
    grid.RowDataBound += grid_RowDataBound; 
    // Your DB access code here... 
    // grid.DataSource = cmd.ExecuteReader(CommandBehavior.CloseConnection); 
    // grid.DataBind(); 
} 

void grid_RowDataBound(object sender, GridViewRowEventArgs e) 
{ 
    if (e.Row.RowType != DataControlRowType.DataRow) 
    return; 
    var dt = (e.Row.DataItem as DbDataRecord).GetDateTime(4); 
    e.Row.Cells[4].Text = dt.ToString("dd.MM.yyyy"); 
} 

结果如下所示。 DateTime Formatting

+0

你有一些生病的技能兄弟 – Ruchan 2014-11-19 09:39:02

1
var currentDateTime = dateTime.Now(); 
var date=currentDateTime.Date; 
+0

你也可以使用 'yourDateObj.ToShortDateString();' – 2017-10-18 09:26:42