Skip to content

Time.DateTimeRounder

NotCoffee418 edited this page Oct 21, 2022 · 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.

Rounding

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
}

Start & End of the month

You can get the first and last milisecond of a month DateTime using GetStartOfMonth(year, month) and GetEndOfMonth(year, month).
Extension methods are also available: dateTimeInstance.StartOfMonth() and dateTimeInstance.EndOfMonth()

// Returns: 2020-01-01 0:00:00
DateTime.Parse("2020-01-15").StartOfMonth();
DateTimeRounder.GetStartOfMonth(2020, 1);

// Returns: 2020-01-31 23:59:59.999
DateTime.Parse("2020-01-15").EndOfMonth();
DateTimeRounder.GetEndOfMonth(2020, 1);

Clone this wiki locally