Round Down to the nearest border in dateTime

In this answer of a similar question, DateTime is rounded to the closing (time) border, the Math.Round method Math.Round not allow rounding the lower border of choice.
Is there a way to calculate the same thing as the lower bound of some time?
The point is, if the time is 10/2/2012 10:52:30, and the choice is an hour than the time: 10/2/2012 10:00:00, if the choice is day, than 10/2/2012 00: 00:00 and etc.

+4
source share
2 answers

If you only need to go to a specific device, I probably would not even bother to use Math.Round or Math.Floor - I would just go with something like:

 switch (unitToRoundDownTo) { case Unit.Second: return new DateTime(old.Year, old.Month, old.Day, old.Hour, old.Minute, old.Second, old.Kind); case Unit.Minute: return new DateTime(old.Year, old.Month, old.Day, old.Hour, old.Minute, 0, old.Kind); case Unit.Hour: return new DateTime(old.Year, old.Month, old.Day, old.Hour, 0, 0, old.Kind); case Unit.Day: return new DateTime(old.Year, old.Month, old.Day, 0, 0, 0, old.Kind); case Unit.Month: return new DateTime(old.Year, old.Month, 1, 0, 0, 0, old.Kind); case Unit.Year: return new DateTime(old.Year, 1, 1, 0, 0, 0, old.Kind); default: throw new ArgumentOutOfRangeException(); } 

This does not work if you need "the next 5 minutes", etc., but for one block of time it is easier to understand and debug than to try to make arithmetic work.

Alternatively, as another answer to the accepted answer to the question you are referring to, you can simply do:

 // tickCount is the rounding interval, eg TimeSpan.FromMinutes(5).Ticks DateTime rounded = new DateTime((old.Ticks / tickCount) * tickCount); 

Please note that this will not help round up to the start of the month or year.

+6
source

Try Math.Floor instead of Math.Round (similar to the post you linked).

+3
source

Source: https://habr.com/ru/post/1389876/


All Articles