Avatar of NerishaB
NerishaBFlag for South Africa

asked on 

C# : Round datetime to the nearest x minutes

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?
C#

Avatar of undefined
Last Comment
NerishaB
Avatar of oxyoo
oxyoo
Flag of Sweden image

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?
Avatar of Shaun Kline
Shaun Kline
Flag of United States of America image

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

Avatar of NerishaB
NerishaB
Flag of South Africa image

ASKER

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



ASKER CERTIFIED SOLUTION
Avatar of Shaun Kline
Shaun Kline
Flag of United States of America image

Blurred text
THIS SOLUTION IS ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
Avatar of NerishaB
NerishaB
Flag of South Africa image

ASKER

Thanks, works great!
C#
C#

C# is an object-oriented programming language created in conjunction with Microsoft’s .NET framework. Compilation is usually done into the Microsoft Intermediate Language (MSIL), which is then JIT-compiled to native code (and cached) during execution in the Common Language Runtime (CLR).

98K
Questions
--
Followers
--
Top Experts
Get a personalized solution from industry experts
Ask the experts
Read over 600 more reviews

TRUSTED BY

IBM logoIntel logoMicrosoft logoUbisoft logoSAP logo
Qualcomm logoCitrix Systems logoWorkday logoErnst & Young logo
High performer badgeUsers love us badge
LinkedIn logoFacebook logoX logoInstagram logoTikTok logoYouTube logo