-1

How to calculate correctly timedifference between two time to show correctly number days hours minutes. The code I wrote shows wrong time span. As I show on the following picture:

enter image description here

My code:

private void button1_Click(object sender, EventArgs e)
{
  TimeSpan ts = dateTimePicker2.Value - dateTimePicker1.Value;
  textBox1.Text = ts.ToString();

  string total = textBox1.Text;
  string[] TotalTIme = textBox1.Text.Split('.');
  textBox1.Text = TotalTIme[0];
}
Nicholas Carey
  • 71,308
  • 16
  • 93
  • 135
Medic2133
  • 21
  • 5
  • You keep rewriting textBox1. Plus the ToString for a TimeSpan has several formatting options – Hans Kesting Dec 29 '21 at 21:16
  • 2
    All you have to do is specify the format. `textBox1.Text = ts.ToString("dd days hh hours");` (I leave it up to you to investigate the formatting). – Andrew Dec 29 '21 at 21:24
  • Does this answer your question? [Showing Difference between two datetime values in hours](https://stackoverflow.com/questions/4946316/showing-difference-between-two-datetime-values-in-hours) – jazb Dec 30 '21 at 01:31

1 Answers1

3

The title of your question is misleading since you actually know how to subtract times to get the TimeSpan, but you don't know how to get the desired information out of it.

You can use TimeSpan.ToString with a custom format string like:

string result = ts.ToString("dd' days, 'hh' hours and 'mm' minutes'");

Note that you also have to quote the spaces as shown above.

If you want the day, hour and minutes as "pure" values, use the appropriate properties.

Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939