Operations with amounts of time and conversion between units of time

Posted on

Question :

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?


Answer :

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;
//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);
//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.


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
//Adiciona 30 minutos, o resultado será 09:30:00 06/06/2017
//Soma a segunda data a primeira, o resultado será 21:00:00 06/06/2017


Leave a Reply

Your email address will not be published. Required fields are marked *