
How-To... - Use The DateDiff Function
The
DateDiff function is used to return the difference between two dates. You
can have teh value returned in seconds, minutes, hours, days, weeks, months,
and years.
Its great when you want to tell how long until a certan date, like a birthday
or Christmas. And the great thing is that it only requires one line!
Setting up the form
To follow this example, create a form(with the Name of frmMain, similar to above, with a two labels(one named lblSeconds, the red label can be called anything)
Add a timer and give it the name tmrWatch.
Adding the code
Below is the full code for the above program. Paste the whole code into the General Declerations part of the Form. Each line of the code is full documented.
'---------------------------------
'How-To use the DateDiff Function
'By David Cowan(Cowan-Creations)
'---------------------------------
'
'This How-To shows you how you can
'use the DateDiff to tell the difference
'between two dates(in this example,
'Christmas.
'
'This source-code is provided 'as is'
'
'http://www.cowan-creations.co.uk/vbhowto/
'E-mail : vbhowto@cowan-creations.co.uk
'-----------------------------------
'Variables to store return values...
Dim iSecond As Long
Dim iMinute As Long
Dim iHour As Integer
Dim iDay As Integer
Dim iMonth As Integer
Dim iYear As Integer
Private Sub Form_Load()
'Get the amount of seconds from now until
'Christmas...
iSecond = DateDiff("s", Now, "25 December")
'Display the value in lblSeconds, using the Standard
'number format...
lblSeconds.Caption = Format(iSecond, "Standard")
End Sub
Private Sub tmrWatch_Timer()
'--------------------------------------------
'This routine is run every seconds and updates
'the label with the new information...
'---------------------------------------------
'Find the amount of second from between now and
'25 December and store in the variable iSecond...
iSecond = DateDiff("s", Now, "25 December")
'These are just other possible example of DateDiff function...
'iMinute = DateDiff("n", Now, "25 December") 'Find amount of minutes...
'iHour = DateDiff("h", Now, "25 December") 'Find the amount of hours...
'iDay = DateDiff("d", Now, "25 December") 'Find the amount of days...
'iMonth = DateDiff("m", Now, "25 December") 'Find the amount of months...
'iYear = DateDiff("y", Now, "25 December") 'Find the amount of years...
'Display the amount of seconds in the label...
lblSeconds.Caption = Format(iSecond, "Standard")
End Sib
Finishing up...
Although this program shows you how to use the DateDiff function, it can improved upon. You can make the program display the amount of seconds, minutes, hours, days, weeks and months. You could also make a message display when it becomes 25 December. There is lots of improvements to be made.
You can download the source code by clicking here