【发布时间】:2011-05-05 01:42:36
【问题描述】:
我有一个DateTime 实例,它有一个日期和一个时间。
如何只提取日期或时间?
【问题讨论】:
我有一个DateTime 实例,它有一个日期和一个时间。
如何只提取日期或时间?
【问题讨论】:
var currentDateTime = dateTime.Now();
var date=currentDateTime.Date;
【讨论】:
yourDateObj.ToShortDateString();
有时你想让你的 GridView 像这样简单:
<asp:GridView ID="grid" runat="server" />
您不想指定任何 BoundField,您只想将网格绑定到 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");
}
这里显示的结果。
【讨论】:
您可以使用 Instance.ToShortDateString() 作为日期,
和 Instance.ToShortTimeString() 用于从同一实例获取日期和时间的时间。
【讨论】:
您也可以使用DateTime.Now.ToString("yyyy-MM-dd") 表示日期,使用DateTime.Now.ToString("hh:mm:ss") 表示时间。
【讨论】:
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
【讨论】:
value.Date + "" 返回date 12:00:00 AM。使用value.Date.ToShortDateString() 来避免这种情况。