How to round up a DateTime to the nearest X minutes with C
Rounding up a DateTime to the nearest specified number of minutes can be useful in a variety of scenarios. Here's a simple and efficient solution for this task:
- Create a RoundUp Utility Function:
public static DateTime RoundUp(DateTime dt, TimeSpan d)
{
return new DateTime((dt.Ticks + d.Ticks - 1) / d.Ticks * d.Ticks, dt.Kind);
}
Copy after login
- Usage:
To round up a DateTime to the nearest 15 minutes, use the following code:
var dt1 = RoundUp(DateTime.Parse("2011-08-11 16:59"), TimeSpan.FromMinutes(15));
// dt1 == {11/08/2011 17:00:00}
Copy after login
- Understanding the Code:
- The RoundUp function takes a DateTime (dt) and a TimeSpan (d) representing the rounding interval.
- The expression (dt.Ticks d.Ticks - 1) calculates the nearest tick value divisible by d.Ticks.
- The division and multiplication by d.Ticks ensures the result is rounded up to the specified interval.
- The new DateTime is created with the computed ticks and the same Kind (local/UTC) as the original DateTime.
Example Output:
- Input: 2011-08-11 16:59
- Result: 2011-08-11 17:00
Additional Notes:
- This approach rounds up to the nearest whole number of intervals, regardless of the time zone.
- To round down, replace (dt.Ticks d.Ticks - 1) with (dt.Ticks 1).
The above is the detailed content of How to Round Up a DateTime to the Nearest X Minutes in C#?. For more information, please follow other related articles on the PHP Chinese website!