简体   繁体   English

仅从 DateTime 对象获取日期或时间

[英]Getting Date or Time only from a DateTime Object

I have a DateTime instance that has a Date and a Time.我有一个包含日期和时间的DateTime实例。 How do I extract only the date or only the time?如何仅提取日期或仅提取时间?

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

您还可以使用DateTime.Now.ToString("yyyy-MM-dd")作为日期,使用DateTime.Now.ToString("hh:mm:ss")作为时间。

You can use Instance.ToShortDateString() for the date,您可以使用Instance.ToShortDateString()作为日期,
and Instance.ToShortTimeString() for the time to get date and time from the same instance.Instance.ToShortTimeString()用于从同一实例获取日期和时间的时间。

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:使用添加了DateOnlyTimeOnly结构的 .NET 6,现在可以像这样获取日期和时间:

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

Docs:文件:

Sometimes you want to have your GridView as simple as:有时你想让你的 GridView 像这样简单:

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

You don't want to specify any BoundField, you just want to bind your grid to DataReader.您不想指定任何 BoundField,只想将网格绑定到 DataReader。 The following code helped me to format DateTime in this situation.以下代码帮助我在这种情况下格式化 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");
}

The results shown here.此处显示的结果。日期时间格式

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM