Home > Blockchain >  DateTime to end of the day C#
DateTime to end of the day C#

Time:11-22

I receive a date like 1.01.2022 h:00, m:00, s:00, ms: 00

What is the best approach to get the date at the end of the day, something like: 01.01.2022 h:23, m:59, s:59, ms: 999?

I tried those 2 ways:

var endOfDay = new TimeSpan(0, 23, 59, 59, 999);
time = time.Add(endOfDay);

and

time = time.AddDays(1).AddMilliseconds(-1);

CodePudding user response:

This removes all doubt down to the resolution of a single tick. In the code below, assume that dateAndTime could include a non-zero time component.

dateAndTime.Date.AddDays(1).AddTicks(-1);

This

  • ensures we are only working with a date that has no time component as our reference point/date
  • moves us to the next date at midnight
  • subtracts a single tick, bringing us back to our reference date with a full-resolution time component (you could do milliseconds if you prefer, just know it's less resolution).

While this works, it's generally better to consider an alternate design that doesn't rely on a time component at all (e.g. use a given date at midnight on the next day to act as a virtual end-of-day for the given reference date).

CodePudding user response:

If you want just to print out the range, the action format is opinion based. If you, however, want to check if some time is within or without the day, please do it as (note >= and <)

 if (timeOfQuestion >= day.Date && timeOfQuestion < day.Date.AddDays(1)) {
   ...
 } 

Using onstructions like endOfDays = time.AddDays(1).AddMilliseconds(-1) is dangerous: please, note that day.Date.AddMilliseconds(999.5) - double value - should be within the day.

  • Related