Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Round UP c# TimeSpan to 5 minutes [duplicate]

Tags:

c#

.net

Possible Duplicate:
How to deal with Rounding-off TimeSpan?

Is there a way to easily round a c# TimeSpan (possible containing more than one day) up so that

0 days 23h 59m becomes 1 days 0 h 0 m?

0 days 23h 47m becomes 0 days 23 h 50 m?

etc?

Here's what i've come up with so far:

int remainder = span2.Minutes % 5;
if (remainder != 0)
{
    span2 = span2.Add(TimeSpan.FromMinutes(5 - remainder));
}

it seems like a lot of code for something rather simple:( Isn't there some kind of built in c# function I can use to round timespans?

like image 232
Michiel Cornille Avatar asked Apr 18 '11 14:04

Michiel Cornille


People also ask

Can you round up in C?

In the C Programming Language, the ceil function returns the smallest integer that is greater than or equal to x (ie: rounds up the nearest integer).

How do I round down in C?

In the C Programming Language, the floor function returns the largest integer that is smaller than or equal to x (ie: rounds downs the nearest integer).

How do I use ceil C?

The ceil() function takes a single argument and returns a value of type int . For example: If 2.3 is passed to ceil(), it will return 3. The function is defined in <math. h> header file.

What is ceil and floor in C?

Ceil and Floor functions in C++ In mathematics and computer science, the floor and ceiling functions map a real number to the greatest preceding or the least succeeding integer, respectively. floor(x) : Returns the largest integer that is smaller than or equal to x (i.e : rounds downs the nearest integer).


2 Answers

Here it is:

var ts = new TimeSpan(23, 47, 00);
ts = TimeSpan.FromMinutes(5 * Math.Ceiling(ts.TotalMinutes / 5));

Or with a grain of sugar:

public static class TimeSpanExtensions
{
    public static TimeSpan RoundTo(this TimeSpan timeSpan, int n)
    {
        return TimeSpan.FromMinutes(n * Math.Ceiling(timeSpan.TotalMinutes / n));
    }
}

ts = ts.RoundTo(5);
like image 166
Anton Gogolev Avatar answered Sep 22 '22 10:09

Anton Gogolev


 static TimeSpan RoundTimeSpan(TimeSpan value)
 {
     return TimeSpan.FromMinutes(System.Math.Ceiling(value.TotalMinutes / 5) * 5);
 }
like image 37
BlueMonkMN Avatar answered Sep 20 '22 10:09

BlueMonkMN