Ottenere la data o l'ora solo da un oggetto DateTime


Risposte:


135
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

1
Non pensavo fosse così ovvio! :)
gideon

value.Date + ""restituisce il date 12:00:00 AM. Utilizzare value.Date.ToShortDateString()per evitare questo.
esitato il

41

Puoi anche usare DateTime.Now.ToString("yyyy-MM-dd")per la data e DateTime.Now.ToString("hh:mm:ss")per l'ora.


1
Ottima scelta. Questo è quello che ottengo rispondendo in fretta. Marc Gravell l'ha inchiodato.
Joshua Smith

5
Direi che stai cercando una stringa abbastanza spesso perché questa risposta abbia valore, però.
GWLlosa

23

È possibile utilizzare Instance.ToShortDateString () per la data
e Instance.ToShortTimeString () per l'ora per ottenere la data e l'ora dalla stessa istanza.



-2

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


4
hai delle abilità malate fratello
Ruchan
Utilizzando il nostro sito, riconosci di aver letto e compreso le nostre Informativa sui cookie e Informativa sulla privacy.
Licensed under cc by-sa 3.0 with attribution required.