2008-10-29 13 views
59

necesito para crear un DateTime medianochemejor manera de crear una medianoche DateTime en C#

que acabo de hacer esto:

DateTime endTime = DateTime.Now; 
endTime.Subtract(endTime.TimeOfDay); 

No han probarlo sin embargo, estoy asumiendo que funciona pero, ¿hay una forma mejor/más limpia?

Respuesta

129

sólo tiene que utilizar foo.Date o DateTime.Today para la fecha de hoy

13

DateTime.Now.AddDays (1) .Date

+6

Creo 'DateTime.Today.AddDays (1)' es mejor que esto. –

10
DateTime endTime = DateTime.Now.Date; 

Ahora vuelve endTime.TimeOfDay.ToString()"00:00:00"

2

Usted puede usar DateTime.Today con segundos exactos de la medianoche.

DateTime today = DateTime.Today; 
    DateTime mid = today.AddDays(1).AddSeconds(-1); 
    Console.WriteLine(string.Format("Today: {0} , Mid Night: {1}", today.ToString(), mid.ToString())); 

    Console.ReadLine(); 

Esto debería imprimir:

Today: 11/24/2016 10:00:00 AM , Mid Night: 11/24/2016 11:59:59 PM 
+0

Esto ayudó mucho y es exactamente lo que quería –

+0

@Matthias es bueno escuchar eso. ¡Aclamaciones! – Aruna

+0

La medianoche es la primera, es el primer segundo del día, no el último. –

0
private bool IsServiceDatabaseProcessReadyToStart() 
    { 
     bool isGoodParms = true; 
     DateTime currentTime = DateTime.Now; 
     //24 Hour Clock 
     string[] timeSpan = currentTime.ToString("HH:mm:ss").Split(':'); 
     //Default to Noon 
     int hr = 12; 
     int mn = 0; 
     int sc = 0; 

     if (!string.IsNullOrEmpty(timeSpan[0])) 
     { 
      hr = Convert.ToInt32(timeSpan[0]); 
     } 
     else 
     { 
      isGoodParms = false; 
     } 

     if (!string.IsNullOrEmpty(timeSpan[1])) 
     { 
      mn = Convert.ToInt32(timeSpan[1]); 
     } 
     else 
     { 
      isGoodParms = false; 
     } 

     if (!string.IsNullOrEmpty(timeSpan[2])) 
     { 
      sc = Convert.ToInt32(timeSpan[2]); 
     } 
     else 
     { 
      isGoodParms = false; 
     } 

     if (isGoodParms == true) 
     { 
      TimeSpan currentTimeSpan = new TimeSpan(hr, mn, sc); 
      TimeSpan minTimeSpan = new TimeSpan(0, 0, 0); 
      TimeSpan maxTimeSpan = new TimeSpan(0, 04, 59); 
      if (currentTimeSpan >= minTimeSpan && currentTimeSpan <= maxTimeSpan) 
      { 
       return true; 
      } 
      else 
      { 
       return false; 
      } 
     } 
     else 
     { 
      return false; 
     } 
    } 
+0

Bienvenido a StackOverflow. Además de proporcionar algún código, proporcione algunos detalles adicionales sobre por qué funciona su solución y cómo difiere de las soluciones anteriores. – buczek

Cuestiones relacionadas