Luke
Luke

Reputation: 5971

Getting Date or Time only from a DateTime Object

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

Answers (7)

GeoB
GeoB

Reputation: 63

Use this: if dt = DateTime.Now;

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

Upvotes: 1

DomenPigeon
DomenPigeon

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

Muhammad Kashif
Muhammad Kashif

Reputation: 91

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

Upvotes: 7

Alexander Chernosvitov
Alexander Chernosvitov

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. DateTime Formatting

Upvotes: -6

Shail Nautiyal
Shail Nautiyal

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

Joshua Smith
Joshua Smith

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

Marc Gravell
Marc Gravell

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

Related Questions