WD: Macro to Determine the Number of Days Between Two Dates

ID: Q105537

The information in this article applies to:

SUMMARY

To determine the number of days between two dates, you can convert dates to serial numbers and subtract one number from the other. The DateValue() function converts a specified date, beginning with December 30, 1899, to a serial number.

MORE INFORMATION

WARNING: ANY USE BY YOU OF THE CODE PROVIDED IN THIS ARTICLE IS AT YOUR OWN RISK. Microsoft provides this macro code "as is" without warranty of any kind, either express or implied, including but not limited to the implied warranties of merchantability and/or fitness for a particular purpose.

The following WordBasic sample macro prompts for a date in the mm/dd/yy format, and returns the number of days between the current date and the specified date.

The DateValue() function converts a specified date, beginning with December 30, 1899, to a serial number.

Syntax: DateValue(DateText$)

Examples

   x = DateValue("12/30/1899")  ' returns 0 or zero
   x = DateValue("12/31/1899")  ' returns 1
   x = DateValue("12/5/1992")   ' returns 33943

The Sgn() function is used to determine if the difference between two dates is a negative(date in the past) or positive(date in the future) number.

   Sub MAIN
      On Error GoTo ErrHandler
      ' Prompt for a date.
      otherdate$ = InputBox$("Enter a date in the mm/dd/yy format")
      ' Convert date to serial format.
      serialdate = DateValue(otherdate$)
      ' Get difference between dates.
      numdays = serialdate - Today()
      ' Determine if difference is past or future.
      If Sgn(numdays) = 1 Then
         MsgBox "The number of days between today and " + otherdate$ + \ 
         " is" + Str$(numdays) + "."
      Else
         MsgBox "The date " + enddate$ + " was" + Str$(Abs(numdays)) \ 
         + " days ago."
      End If
      If Err <> 0 Then MsgBox "Please enter a valid date."
   End Sub

Additional query words: w6macroexample calculate difference
Keywords          : kbmacroexample winword word6 word7 word95 
Version           : WINDOWS: 6.0, 6.0a, 6.0c, 7.0, 7.0a
Platform          : WINDOWS
Issue type        : kbhowto

Last Reviewed: February 13, 1999