The starting time is entered in textBox1 - 8:55 (or 08:55)
The final time is entered in textBox2 - 9:02 (or 09:02)

QUESTION
How to calculate the duration and add to textBox3 ?
In this case, it should work out - 7 minutes.

enter image description here

  • Instead of a TextBox use the DateTimePicker to enter the time. - Alexander Petrov

3 answers 3

  //получаем данные string inputString1 = textbox1.Text; string inputString2 = textbox2.Text; //конвертируем данные TimeSpan time1, time2; if (!TimeSpan.TryParse(inputString1, out time1)) { //выводим пользователю ошибку о том что пусть нормально введет время в textbox1 } if (!TimeSpan.TryParse(inputString2, out time2)) { //выводим пользователю ошибку о том что пусть нормально введет время в textbox2 } //Выводим данные пользователю в формате hh:mm textbox3.Text = (time2 - time1).ToString(@"hh\:mm"); //Либо, как подсказали из коментариев, выводим интервал только в минутах textbox3.Text = (time2 - time1).TotalMinutes.ToString("###############"); 
  • @ koks_rs4per And how to make the textBox3 display the interval only in minutes and in the range from 1 to infinity (roughly speaking). Those. there it is supposed to place the values ​​59 minutes, 60 minutes, 90 minutes. 120 min etc. But not 01:00, 01:20, etc. Thank you all for the answer. - koverflow
  • one
    textbox3.Text = (time2 - time1).TotalMinutes.ToString("###############"); - 4per
  • @koverflow, try to clarify the issue by editing it. - 4per

You can try through TimeSpan . Only at the beginning you have to convert the lines to DateTime .

 DateTime oldDate = new DateTime(2016, 11, 25, 11, 25, 0); DateTime newDate = new DateTime(2016, 11, 25, 11, 28, 0); TimeSpan ts = newDate - oldDate; int differenceInMins = ts.Minutes; 

The resulting result is converted to a string and textBox to the textBox . If a difference of more than 60 minutes is allowed, use the appropriate TimeSpan members. For example:

 int differenceInMins = (ts.Hours*60)+ts.Minutes; 
  • And why is there a datetime? Why not use TimeSpan right away? - koks_rs
  • one
    @koks_rs well scalable with datetime. When it will be necessary to take away from the night of 23 pm - it will be easier - 4per
  • Streletz you have errors. What happens if the difference in minutes is 60 minutes or more? - 4per
  • @ 4per, there are no errors. If the difference is supposed to be more than 60 minutes, the corresponding members of TimeSpan simply involved and that's it. The principle itself remains unchanged. - Streletz

See the TimeSpan structure. Algorithm for solving the problem:

  1. Translate date strings into DateTime data type.
  2. Declare a variable of type TimeSpan . Its value will be equal to the time difference.
  3. Write to the textbox end result.