DateTime
math can be confusing at first. But it doesn't really matter if they are DateTimePicker
controls or variables because myDateTimePicker.Value
is a DateTime
Type. So, you can mix and match variables and controls such as Arrival as Now and Departure from a picker, and just use subtraction:
Dim arrivaldate As DateTime = DateTime.Now
Dim departuredate As DateTime = Me.DeparturePicker.Value
Dim DaysStayed as Int32 = departuredate.Subtract(arrivaldate).Days
The thing to remember is that the result is a TimeSpan object. If you look at the structure, you'll see it provides the time elapsed in units from Days
to Ticks
.
The code above plucks the Days
value from the TimeSpan
without creating a temp TimeSpan
var. Another way:
Dim tsHotelStay = detarturedate.Value - arrivalDate
wholeDays = tsHotelStay.Days ' e.g 7
totalDays = tsHotelStay.TotalDays . e.g. 7.53
totalHrs = tsHotelStay.TotalHours . eg 180.397
This time, the code does create a TimeSpan
variable (tsHotelDay
). Note that all the properties are available in whole and fractional forms (except Ticks).
Finally, the 2 subtraction methods shown (DateTime.Subtract(dt)
and myTs = dtA - dtB
) are functionally identical: both return a TimeSpan object.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…