Round up minutes C#

Asked

Viewed 251 times

2

Guys, I have a problem that is, I need to round up the minutes of an hour, for example: if the time is 12:28 I need it to turn 12:30, I always need to round it up, does anyone know how to fix this? Remembering that I am working with Timespan. If anyone can help me I appreciate.

  • 1

    take a look in that reply, I think it solves.

  • Always for the biggest? 12:21 turns to 12:30 or 12:20?

  • This always goes on and on.

1 answer

4


You can do it this way:

public static class TempoUtils{
    private static int MultiploSeguinte(int n, int m){
        var resto = n % m;
        if(resto == 0) return n;
        var faltam = m - resto;
        return n + faltam;
    }

    public static TimeSpan CeilMinutos(this TimeSpan tempo, int multiplo){
        var multiploSeguinte = MultiploSeguinte(tempo.Minutes, multiplo);
        return new TimeSpan(tempo.Hours, multiploSeguinte, tempo.Seconds);
    }   

}

void Main()
{
    var tempo = new TimeSpan(12, 21, 00);
    tempo.CeilMinutos(30).Dump();
}

There is a lot going on so it is worth an explanation. The function MultiploSeguinte Calculates the next multiple (or the number itself if it is a multiple) of a number depending on the’m parameter'.

The function CeilMinutos uses MultiploSeguinte but works with the structure TimeSpan which is the structure that Voce is interested in.

I have made use of extension methods that allow you to access static methods as if they were instantiation methods. In practice this allows you to call tempo.CeilMinutos instead of TempoUtils.CeilMinutos(tempo, 30)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.