Reputation: 5971
I have a DateTime
instance that has a Date and a Time.
How do I extract only the date or only the time?
Upvotes: 132
Views: 267924
Reputation: 63
Use this: if dt = DateTime.Now;
var DateOnly = new DateTime(dt.Year, dt.Month, dt.Day);
Upvotes: 1
Reputation: 1127
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:
Upvotes: 31
Reputation: 91
var currentDateTime = dateTime.Now();
var date=currentDateTime.Date;
Upvotes: 7
Reputation: 698
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.
Upvotes: -6
Reputation: 494
You can use Instance.ToShortDateString() for the date,
and Instance.ToShortTimeString() for the time to get date and time from the same instance.
Upvotes: 38
Reputation: 1004
You can also use DateTime.Now.ToString("yyyy-MM-dd")
for the date, and DateTime.Now.ToString("hh:mm:ss")
for the time.
Upvotes: 61
Reputation: 1063994
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
Upvotes: 176