Best way to create Midnight DateTime in C #

I need to create a midnight DateTime

I just did this:

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

Don't test it yet, I assume it works, but is there a better / cleaner way?

+66
c # datetime
Oct 29 '08 at 9:29
source share
7 answers

Just use foo.Date or DateTime.Today for today's date

+147
Oct 29 '08 at 9:31
source share
+13
Oct 29 '08 at 9:35
source share

DateTime.Today

+12
Oct 29 '08 at 9:32
source share
 DateTime endTime = DateTime.Now.Date; 

Now endTime.TimeOfDay.ToString() returns "00:00:00"

+11
Oct 29 '08 at 9:40
source share

You can use DateTime.Today with the exact seconds of midnight.

  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(); 

This should print:

 Today: 11/24/2016 10:00:00 AM , Mid Night: 11/24/2016 11:59:59 PM 
+5
Nov 24 '16 at 7:32
source share
 var dateMidnight = DateTime.ParseExact(DateTime.Now.ToString("yyyyMMdd"), "yyyyMMdd", CultureInfo.InvariantCulture); 
0
Jan 22 '19 at 20:26
source share
  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; } } 
-one
Jan 24 '17 at 19:41
source share



All Articles