C# : Round datetime to the nearest x minutes

NerishaB
NerishaB used Ask the Experts™
on
hi,

I need to round a datetime to the nearest x minutes, where x is a decimal value.

For eg. DateTime ClockTime = 2011/04/11 07:35:23
             Double x = 0.25

Result : 2011/04/11 07:45:23

Can anyone help me here?
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®

Commented:
Hi,

Not sure I follow what you want to accomplish... could you please try and further explain the scenario?
Also is the double "x=0.25" equal to 25 minutes?
Shaun KlineLead Software Engineer

Commented:
Something like this?
(If you want to remove the seconds, add a .AddSeconds(-ClockTime.Second) to the last Result = line.
DateTime ClockTime =  DateTime.Now;
            DateTime Result;
            Double x = 0.25;

            if (ClockTime.Minute % (60 * x) == 0 && ClockTime.Second == 0) //  Time is at the x minute.
                Result = ClockTime;
            else
                Result = ClockTime.AddMinutes(-ClockTime.Minute % (60 * x)).AddMinutes(60 * x);

Open in new window

Author

Commented:
Thanks Shaun

What I actually want is this:

DateTime ClockTime =  DateTime.Now;
            DateTime Result;
            Double x = 0.25;
            RoundUp = Yes

if Roundup = "YES" then round up by 15 mins, for example, if I clocked in at 8:05, and roundedUp is 0.25, then I need to change the ClockTime to 8:15,  

if RoundUp is "No" then ClockTime must be rounded to the closest 15 mins, being 8:00am



Lead Software Engineer
Commented:
OK, then...
DateTime ClockTime =  DateTime.Now;
            DateTime Result;
            Double x = 0.25;
            Boolean RoundUp = true;

            if (ClockTime.Minute % (60 * x) == 0 && ClockTime.Second == 0) //  Time is at the x minute.
                Result = ClockTime;
            else
            {
                if (RoundUp || (ClockTime.Minute % (60 * x)) > ((60 * x) / 2))
                    Result = ClockTime.AddMinutes(-ClockTime.Minute % (60 * x)).AddMinutes(60 * x);
                else
                    Result = ClockTime.AddMinutes(-ClockTime.Minute % (60 * x));
            }

Open in new window

Author

Commented:
Thanks, works great!

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial