Question Difference between 2 datetimes in hours, minutes

curlyq

New member
Joined
Apr 5, 2015
Messages
4
Programming Experience
Beginner
What would be the best method to calculate the difference between 2 datetimes and get the resulting hours and minutes. I have two datetimes, formatted to mm/dd/yyy hh:mm. I would like to show the result of the difference between these two in a textbox or label control in the form of hh:mm. I am using vb.net 3.5. Thanks for any help.
 
I have two datetimes, formatted to mm/dd/yyy hh:mm.

No, you don't. A DateTime has no format at all. A DateTime is just a number that represents the elapsed time from a specific reference time. Format is only an issue when representing a date/time in a String. When converting a DateTime to a String for display purposes, you need to specify the format of the String. Likewise, when converting a String to a DateTime, e.g. when a user enters data into a form, you need to specify the format of the String in order to know how to parse it.

So, you just have two DateTimes. In order to do what you want, you simply subtract one DateTime from the other to produce a TimeSpan and then get the appropriate property values from that, e.g. Hours, Minutes or TotalHours. To display the time difference, if you were using .NET 4.0 then you could simply call ToString on the TimeSpan and provide a format specifier. In .NET 3.5 you have two options:

1. Create a DateTime with your TimeSpan as the time portion and then call ToString on that to display just the time part. This will only work if the time is less than a full day.
2. Call String.Format and format the Hours and Minutes of your TimeSpan separately.
 
Back
Top