5

Is there a function to round off the datetime to 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 have written the below function, but it 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 appreciated.

Tarun Arora
  • 4,692
  • 4
  • 30
  • 40

2 Answers2

12

Apply the modulo 15 to the datetime Minute property and subtract that 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 have created a zero seconds datetime. If you need to remove also the seconds

DateTime dt = new DateTime(2013,5,28, 15, 59,45);
dt = dt.AddMinutes(-(dt.Minute % 15)).AddSeconds(-dt.Second);
Steve
  • 213,761
  • 22
  • 232
  • 286
3

Change you method to:

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

Checked this it works for me.

TheKingDave
  • 926
  • 1
  • 8
  • 16