calculate no of days from 2 dates

banks

Well-known member
Joined
Sep 7, 2005
Messages
50
Programming Experience
Beginner
VB.NET:
    Public Sub calculateDays()
        ' Calendar Days
        Dim dtpDateCarSent As New DateTime
        Dim dtpDateClosed As New DateTime
        Dim dys As Integer = dtpDateClosed.Date.Subtract(dtpDateCarSent.Date).Days
    End Sub

Hi, im trying to use the above code but it isnt working... I am trying to calculate the no of days between two dates that i choose on my form using a dateTimepicker control. So for example if dateCarSent is 01/01/2006 and dateCarClosed is 05/01/2006, the answer would be 4 days.

Any help much apreciated,

Al
 
VB.NET:
Dim lngHowLong As Long
Dim date1 As Date = dtpDateCarSent.Text
Dim date2 As Date = dtpDateClosed.Text
 
lngHowLong = DateDiff("d", date1, date2)
MsgBox("There are " & lngHowLong & " days between the two dates.")
 
Last edited by a moderator:
VB.NET:
[SIZE=2][COLOR=#0000ff]Dim[/COLOR][/SIZE][SIZE=2] d1 [/SIZE][SIZE=2][COLOR=#0000ff]As[/COLOR][/SIZE][SIZE=2] DateTime = [/SIZE]dtpDateCarSent.Text
[SIZE=2][COLOR=#0000ff]Dim[/COLOR][/SIZE][SIZE=2] d2 [/SIZE][SIZE=2][COLOR=#0000ff]As[/COLOR][/SIZE][SIZE=2] DateTime = [/SIZE][SIZE=2][COLOR=#0000ff][COLOR=#000000]dtpDateClosed.Text[/COLOR]
[/COLOR][/SIZE][SIZE=2][/SIZE][SIZE=2][COLOR=#0000ff]Dim[/COLOR][/SIZE][SIZE=2] tmSpan [/SIZE][SIZE=2][COLOR=#0000ff]As[/COLOR][/SIZE][SIZE=2] TimeSpan = d2.Subtract(d1)[/SIZE]
MessageBox.Show(tmSpan.TotalDays)
 
kulrom/banks.. Minor point of note..

I really dont recommend you do this:
VB.NET:
[COLOR=#0000ff]Dim[/COLOR][SIZE=2] d1 [/SIZE][SIZE=2][COLOR=#0000ff]As[/COLOR][/SIZE][SIZE=2] DateTime = [/SIZE]dtpDateCarSent.[B]Text[/B]

two reasons:
1) Option Strict disallows implicit conversions from string, to date. Programming with Option Strict enabled is a good idea, as it can prevent you making some unsafe assumptions about conversions between variable types that could fail when the program is running

2) There is no guarantee that the Text represented in a DateTimePicker control is convertable to a date. If you custom format a DTP with the format string yyyyMMdd you will see it have e.g. 20060701. VB has no chance of converting this to a date


Bottom line?
Use DateTimePicker.Value instead. This will give you a date.. and kulrom's code can then be shortened to:
VB.NET:
[B]Dim dys as Integer = dtpDateCarSent.Value.Subtract(dtpDateClosed.Value).TotalDays[/B]
 
Last edited by a moderator:
Back
Top