Geeks With Blogs

News



Add to Google

Tim Hibbard CEO for EnGraph software

times

Our software will automatically generate pick up and drop off times based on distance of trip, how many other people are on the bus, how long it takes to drop them off, etc. We display these times in our custom TimeSpinner control based on WPF Extended Toolkit’s button spinner.

Since the computer is generating the time, they are often not human-friendly. 6:00 AM is a lot easier to remember than 6:03 AM. So we give the users the option to modify these times. Using the spinners, they can adjust the time 5 minutes up or 5 minutes down. However, 6:08 is still difficult to remember, so what we really need is to be able to round up (or down) to the nearest 5 minutes, then adjust in 5 minute increments after that.

So 6:03 AM to 6:05 AM to 6:10 AM to 6:15 AM and likewise, round down from 6:03 AM to 6:00 AM to 5:55 AM to 5:50 AM.

We used an extension method to accomplish this. Note that it accepts increments other than 5 minutes, that’s just what we use.

   1: /// <summary>
   2: /// Adds or subtracts a value to a date time rounding it to
   3: /// multiples of the entered value
   4: /// </summary>
   5: /// <param name="dt">this</param>
   6: /// <param name="value">Amount to add or subtract</param>
   7: /// <returns>Adjusted DateTime</returns>
   8: public static DateTime AddMinutesRoundUp(this DateTime dt, int value)
   9: {
  10:     int delta = dt.Minute % value;
  11:     int subtractDeltaFrom = 0;
  12:     //if value to add is negative, we want to round down
  13:     //to nearest delta value
  14:     if (value < 0)
  15:     {
  16:         //but only if delta is more than 0. If delta is 0, 
  17:         //then we are already rounded down
  18:         if (delta > 0)
  19:         {
  20:             subtractDeltaFrom = Math.Abs(value); 
  21:         }
  22:         
  23:     }
  24:     return dt.AddMinutes(subtractDeltaFrom - delta).AddMinutes(value);
  25: }
Posted on Tuesday, April 12, 2011 8:26 AM EnGraph , .NET , WPF | Back to top


Comments on this post: Smarter DateTime.AddMinutes

# re: Smarter DateTime.AddMinutes
Requesting Gravatar...
It is the right tool for my day to day work. Thank for this code. I will share this to my brother.
Left by Antibiotics for Horses on Oct 10, 2011 4:21 AM

# re: Smarter DateTime.AddMinutes
Requesting Gravatar...
thanks this helps for my programming course
Left by Dana on Oct 18, 2012 7:55 AM

Your comment:
 (will show your gravatar)


Copyright © Tim Hibbard | Powered by: GeeksWithBlogs.net