Skip to content

Time.DateTimeRounder

NotCoffee418 edited this page Oct 30, 2021 · 2 revisions

DateTimeRounder is a tool which helps to round a DateTime to the nearest minute, hour, day or any other TimeSpan between 1ms and 1 day you need.
Values larger than 1 day are not restricted but become inaccurate, so it's not recommended.

Usage

using CoffeeToolkit.Time;
using CoffeeToolkit.Data.Time; // optional: for predefined timespans

void DateTimeRounderExamples()
{
    DateTime unroundedTime = DateTime.Parse("2021-10-21 10:34:12.731");

    // Round down by Hour
    DateTime roundedDown = DateTimeRounder.RoundDown(unroundedTime, Interval.Hour);
    Console.WriteLine(roundedDown);
    // Output: 21/10/2021 10:00:00
    
    DateTime roundedUp = DateTimeRounder.RoundUp(unroundedTime, Interval.Hour);
    Console.WriteLine(roundedUp);
    // Output: 21/10/2021 11:00:00

    DateTime roundedToNearest = DateTimeRounder.RoundToNearest(unroundedTime, Interval.Hour);
    Console.WriteLine(roundedUp);
    // Output: 21/10/2021 11:00:00

    // Round by custom interval
    TimeSpan customInterval = TimeSpan.FromHours(4);
    DateTime roundedDownFourHour = DateTimeRounder.RoundDown(unroundedTime, customInterval);
    Console.WriteLine(roundedDownFourHour);
    // Output: 21/10/2021 08:00:00
}

Additionally you can also simplify the invocation importing CoffeeTools.Extensions like so:

using CoffeeToolkit.Time;
using CoffeeToolkit.Data;
using CoffeeToolkit.Extensions;

void DateTimeRounderExamplesWithExtension() 
{
    // Sample input
    DateTime unroundedTime = DateTime.Parse("2021-10-21 10:34:12.731");

    // Output
    DateTime roundedTime = unroundedTime.RoundToNearest(Interval.Hour);
    Console.WriteLine(roundedTime);
    // Output: 21/10/2021 11:00:00
}

Clone this wiki locally