Home > Backend Development > C++ > How to Round Up a DateTime to the Nearest X Minutes in C#?

How to Round Up a DateTime to the Nearest X Minutes in C#?

Susan Sarandon
Release: 2025-01-06 18:59:44
Original
706 people have browsed it

How to Round Up a DateTime to the Nearest X Minutes in C#?

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:

  1. 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
  1. 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
  1. 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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template