0

I have been building a program where i need to calculate the difference between different dates....... its a network outage program i want to calculate down time between different dates e.g network was down on 08/06/2013 9:00 AM and was restored on 09/06/2013 10:00 PM.... the down time should be 34 hours......... i have been able to calculate the days but i want this in hour format so anyone please help me............. i m using datetimePicker to get the date and time at the same time.

i have been using the below mentioned code for that purpose

dateTimePicker1.Format = DateTimePickerFormat.Custom;


dateTimePicker1.CustomFormat = " dd/MM/yyyy hh:mm tt ";


dateTimePicker2.Format = DateTimePickerFormat.Custom;


dateTimePicker2.CustomFormat = " dd/MM/yyyy hh:mm tt "; 



ts1 = dt2.Subtract(dt1);


 richTextBox1.Text = "The Hours Difference is:\t" + dt2.Subtract(dt1).Hours + "\n The Minute Difference is:\t" + dt2.Subtract(dt1).Minutes;
Abeer Islam
  • 33
  • 1
  • 2
  • 7

2 Answers2

1

You can use the .Net timespan class for this.

System.DateTime firstDate = new System.DateTime(2006, 9, 13, 12, 0, 0);
System.DateTime SecondDate = new System.DateTime(2006, 9, 13, 0, 0, 0);
System.TimeSpan diffResult = firstDate.Subtract(SecondDate);

diffResult will contain all the differences in firstDate and secondDate in year, month, day, hour, minutes and seconds.

You can get any datepart from this:

diffResult.Days
diffResult.Hours
diffResult.Minutes
etc.
Mat
  • 188,820
  • 38
  • 367
  • 383
0

You need

dt2.Subtract(dt1).TotalHours

and

dt2.Subtract(dt1).TotalMinutes
Damith
  • 59,353
  • 12
  • 95
  • 149
  • here is sample output i m getting in respect to the values i provide like if i want to calculate difference between 08/06/2013 9:00 AM and 09/06/2013 9:45 AM ........... it should provide me with output like 24 hours and 45mins however hour difference is 24.75 and min is 45 – Abeer Islam Jun 09 '13 at 14:18
  • it is depend on your requirement, you can cast it to int value if you don't need minutes. – Damith Jun 09 '13 at 14:33
  • thanks much appreciated actually i m using the minutes property as well – Abeer Islam Jun 09 '13 at 14:45
  • one more question though if the input provided is like 09/06/2013 8:00 PM and 2nd one is 09/06/2013 8:45 PM.......... the output still shows 1 hr difference where as it should show 0 hrs and 45 mins any idea or should i just use if else conditions to control these things – Abeer Islam Jun 09 '13 at 14:50