How to get total hours using TimeSpan in VB.NET
I am using the TimeSpan function in VB.NET to get the total number of hours in a billing month.
I have 30 days in a billing month, so presumably I have 720 intervals. Using Timespan normally, I would get 696 intervals. But I add the day to my "todate" to get my correct total hours. This is my code:
Dim TS As TimeSpan
Dim totalhours As Integer
Dim todate As DateTime = #11-30-2014#
Dim fromdate As DateTime = #11-01-2014#
TS = todate.AddDays(1).Subtract(fromdate)
totalhours = TS.TotalHours
However, I don't think manipulating my input date (adding the day) is best practice. Is there a way to customize the timepan function to get the total clock?
+3
source to share
1 answer
This is because you did not specify a time range. Only one date will be 12AM for the time portion.
Dim TS As TimeSpan
Dim totalhours As Integer
Dim todate As DateTime = #11-30-2014 11:59:59 PM#
Dim fromdate As DateTime = #11-01-2014#
TS = todate.Subtract(fromdate)
totalhours = TS.TotalHours
It will be 1 hour shy.
Dim TS As TimeSpan
Dim totalhours As Integer
Dim todate As DateTime = #12-01-2014#
Dim fromdate As DateTime = #11-01-2014#
TS = todate.Subtract(fromdate)
totalhours = TS.TotalHours
Will get the correct amount as it includes the time between two dates.
+2
source to share