DotNet rounding time and time up to 15 minutes

Is there a function to round the date and time to the last quarter?

Example...

08:03:00 becomes 08:00:00 08:14:00 becomes 08:00:00 08:15:00 stays 08:15:00 08:16:00 becomes 08:15:00 08:29:00 becomes 08:15:00 08:45:00 stays 08:45:00 08:55:00 becomes 08:45:00 09:01:00 becomes 09:00:00 

I wrote the following function , but returns the next quarter ...

 private DateTime RoundUpToPreviousQuarter(DateTime date, TimeSpan d) { return new DateTime(((date.Ticks + d.Ticks - 1) / d.Ticks) * d.Ticks); } // call the method this.RoundUp(time, TimeSpan.FromMinutes(15)); 

Any inputs are appreciated.

+2
c #
source share
2 answers

Apply modulo 15 to the Minute datetime property and subtract this value from the same property

 DateTime dt = new DateTime(2013,5,28, 15, 59,0); dt = dt.AddMinutes(-(dt.Minute % 15)); 

In this example, I created a date and time with zero seconds. If you need to also delete seconds

 DateTime dt = new DateTime(2013,5,28, 15, 59,45); dt = dt.AddMinutes(-(dt.Minute % 15)).AddSeconds(-dt.Second); 
+7
source share

Change your method to:

 private DateTime RoundUpToPreviousQuarter(DateTime date, TimeSpan d) { return new DateTime(((date.Ticks) / d.Ticks) * d.Ticks); } 

Verified, this works for me.

+3
source share

All Articles