Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a simple function for rounding a DateTime down to the nearest 30 minutes, in C#?

Tags:

c#

datetime

For example:

2011-08-11 16:59 becomes 2011-08-11 16:30

like image 666
Dinesh Avatar asked Apr 11 '12 05:04

Dinesh


1 Answers

DateTime RoundDown(DateTime dt, TimeSpan d)
{
    return new DateTime((dt.Ticks / d.Ticks) * d.Ticks);
}

Example:

var dt1 = RoundDown(DateTime.Parse("2011-08-11 16:59"), TimeSpan.FromMinutes(30));
// dt1 == {11/08/2011 16:30:00}

var dt2 = RoundDown(DateTime.Parse("2011-08-11 17:00"), TimeSpan.FromMinutes(30));
// dt2 == {11/08/2011 17:00:00}

var dt3 = RoundDown(DateTime.Parse("2011-08-11 17:01"), TimeSpan.FromMinutes(30));
// dt3 == {11/08/2011 17:00:00}
like image 187
dtb Avatar answered Oct 04 '22 19:10

dtb