Ho DateTimeun'istanza che ha una data e un'ora. Come estraggo solo la data o solo l'ora?
Risposte:
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
value.Date + ""restituisce il date 12:00:00 AM. Utilizzare value.Date.ToShortDateString()per evitare questo.
Puoi anche usare DateTime.Now.ToString("yyyy-MM-dd")per la data e DateTime.Now.ToString("hh:mm:ss")per l'ora.
È possibile utilizzare Instance.ToShortDateString () per la data
e Instance.ToShortTimeString () per l'ora per ottenere la data e l'ora dalla stessa istanza.
var currentDateTime = dateTime.Now();
var date=currentDateTime.Date;
yourDateObj.ToShortDateString();
A volte vuoi avere GridView semplice come:
<asp:GridView ID="grid" runat="server" />
Non vuoi specificare alcun BoundField, vuoi solo associare la tua griglia a DataReader. Il codice seguente mi ha aiutato a formattare DateTime in questa situazione.
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");
}
I risultati mostrati qui.
