仅从 DateTime 对象获取 Date 或 Time

我有一个 DateTime实例,它有一个 Date 和一个 Time。 如何只提取日期或时间?

180136 次浏览
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

You can also use DateTime.Now.ToString("yyyy-MM-dd") for the date, and DateTime.Now.ToString("hh:mm:ss") for the time.

You can use Instance.ToShortDateString() for the date,
and Instance.ToShortTimeString() for the time to get date and time from the same instance.

Sometimes you want to have your GridView as simple as:

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

You don't want to specify any BoundField, you just want to bind your grid to DataReader. The following code helped me to format DateTime in this situation.

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");
}

The results shown here. DateTime Formatting

var currentDateTime = dateTime.Now();
var date=currentDateTime.Date;

With the .NET 6 which added DateOnly and TimeOnly structs it's now possible to get the date and time like this:

var dateTime = DateTime.Now;
var date = DateOnly.FromDateTime(dateTime);
var time = TimeOnly.FromDateTime(dateTime);

Docs:

Use this: if dt = DateTime.Now;

var DateOnly = new DateTime(dt.Year, dt.Month, dt.Day);