Round minutes C #

2
I have a problem that is the following, I need to round the minutes of an hour, for example: if the time is 12:28 I need it to turn 12:30, I need to always round to bigger, does anyone know how to solve this ? Remembering that I'm working with TimeSpan. If anyone can help me, I appreciate it.

    
asked by anonymous 24.04.2018 / 16:07

1 answer

4

You can do this as follows:

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's a lot going for it so it's worth an explanation. The MultiploSeguinte function calculates the next multiple (or the number itself if it is a multiple) of a number depending on the 'm' parameter.

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

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

    
24.04.2018 / 19:19