Operations with amounts of time and conversion between units of time

3

Is there a library specialized in the manipulation of quantities and units of time? It allows the conversion of / in milliseconds, seconds, minutes and operations of addition and subtraction of amounts of time.

Native to c# I have not found anything that does not require a lot of effort and conversion calculations.

Or if there is natively how you could get the total hours by adding two amounts of time, for example:

03:20 + 03:50 =?

Is there a way to do this without having to unlock the hours and minutes, making validations for when the minutes go from 59 to an extra hour?

    
asked by anonymous 06.06.2017 / 00:29

2 answers

18

You can add the usual hours in C #. To do this, just make sure the time is a time slot .

You can perform operations seamlessly with formats of type TimeSpan and DateTime (this one for dates along with schedules).

To add two times, or more, just add up normally. See the example below:

var time = new TimeSpan(3, 20, 0);
var time2 = new TimeSpan(3, 50, 0);

var total = time + time2;
Console.WriteLine(total);
//Resultado: 07:10:00

Example in .NET Fiddle.

It's worth mentioning that you have several methods to use with or TimeSpan . With them, you get more accurate results.

An example is if you add values that exceed 24 hours. See the example below:

var time = new TimeSpan(20, 20, 0);
var time2 = new TimeSpan(13, 50, 0);

var total = time.Add(time2);
Console.WriteLine(total.TotalHours);
//Resultado: 34.1666666666667

Example in .NET Fiddle.

See the image below to better understand the values you have without having to "validate" (as you said in your question):

Ifyou'dliketoseemorewaystodothis,hereareafewexamples in our big brother.

    
06.06.2017 / 14:21
6

It's very easy to manipulate dates and times if they are in DateTime format

//Cria uma nova data 09:00:00 06/06/2017
DateTime teste = new DateTime(2017, 6, 6, 9, 0, 0);
//Cria uma nova data 12:00:00 06/06/2017
DateTime teste2 = new DateTime(2017, 6, 6, 12, 0, 0);

//Adiciona uma hora, o resultado será 10:00:00 06/06/2017
teste.AddHours(1);
//Adiciona 30 minutos, o resultado será 09:30:00 06/06/2017
teste.AddMinutes(30)
//Soma a segunda data a primeira, o resultado será 21:00:00 06/06/2017
teste.Add(teste2.TimeOfDay());
    
06.06.2017 / 14:27