Getting Date or Time only from a DateTime Object
C#.NetDatetimeC# Problem Overview
I have a DateTime
instance that has a Date and a Time.
How do I extract only the date or only the time?
C# Solutions
Solution 1 - C#
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
Solution 2 - C#
You can also use DateTime.Now.ToString("yyyy-MM-dd")
for the date, and DateTime.Now.ToString("hh:mm:ss")
for the time.
Solution 3 - C#
You can use Instance.ToShortDateString() for the date,
and Instance.ToShortTimeString() for the time to get date and time from the same instance.
Solution 4 - C#
var currentDateTime = dateTime.Now();
var date=currentDateTime.Date;
Solution 5 - C#
With the .NET 6 which added DateOnly
and TimeOnly
structs it's not possible to get the date and time like this:
var dateTime = DateTime.Now;
var date = DateOnly.FromDateTime(dateTime);
var time = TimeOnly.FromDateTime(dateTime);
Docs:
Solution 6 - C#
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.