lulutanseco
lulutanseco

Reputation: 423

How to get inclusive total hours using TimeSpan in VB.NET

I'm using TimeSpan function in VB.NET to get the total hours in a billing month.

I have 30 days in a billing month, so supposedly, I have 720 intervals. Using Timespan normally, I would get 696 intervals. But I add a day in my "todate" in order 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 that manipulating my input date (by adding a day) is the best practice. Is there any way to configure the timespan function to get the inclusive total hours?

Upvotes: 3

Views: 730

Answers (1)

OneFineDay
OneFineDay

Reputation: 9024

That is because you did not supply the time range. The date alone will be 12AM for the time part.

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

That will be 1 hours 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 since it is inclusive of time between the two dates.

Upvotes: 2

Related Questions