<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="VB6Parse Library Reference - datediff - Datetime">
<title>datediff - Datetime - VB6Parse Library Reference</title>
<link rel="stylesheet" href="../../../assets/css/style.css">
<link rel="stylesheet" href="../../../assets/css/docs-style.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/styles/github-dark.min.css">
<script src="../../../assets/js/theme-switcher.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/highlight.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/languages/vbnet.min.js"></script>
<script>hljs.highlightAll();</script>
</head>
<body>
<header class="docs-header">
<div class="container">
<h1><a href="../../../index.html">VB6Parse</a> / <a href="../../../library/index.html">Library</a> / <a href="../../../library/functions/datetime/index.html">Datetime</a> / datediff</h1>
<p class="tagline">VB6 Library Reference</p>
</div>
</header>
<nav class="docs-nav">
<div class="container">
<a href="../../../index.html">Home</a>
<a href="../../../library/index.html">Library Reference</a>
<a href="../../../documentation.html">Documentation</a>
<a href="https://docs.rs/vb6parse" target="_blank">API Docs</a>
<a href="https://github.com/scriptandcompile/vb6parse" target="_blank">GitHub</a>
<button id="theme-toggle" class="theme-toggle" aria-label="Toggle theme">
<span class="theme-icon">🌙</span>
</button>
</div>
</nav>
<main class="container">
<article class="library-item">
<h1 id="datediff-function">DateDiff Function</h1>
<p>Returns a <code>Variant</code> (<code>Long</code>) specifying the number of time intervals between two specified dates.</p>
<h2 id="syntax">Syntax</h2>
<pre><code class="language-vbnet">DateDiff(interval, date1, date2[, firstdayofweek[, firstweekofyear]])</code></pre>
<h2 id="parameters">Parameters</h2>
<ul>
<li><strong>interval</strong>: Required. <code>String</code> expression that is the interval of time you want to use
to calculate the difference between date1 and date2. See Interval Settings for values.</li>
<li><strong>date1</strong>, <strong>date2</strong>: Required. <code>Variant</code> (<code>Date</code>) values that you want to use in the calculation.</li>
<li><strong>firstdayofweek</strong>: Optional. Constant that specifies the first day of the week.
If not specified, Sunday is assumed. See <code>FirstDayOfWeek</code> Constants.</li>
<li><strong>firstweekofyear</strong>: Optional. Constant that specifies the first week of the year.
If not specified, the first week is assumed to be the week containing January 1.
See <code>FirstWeekOfYear</code> Constants.</li>
</ul>
<h2 id="interval-settings">Interval Settings</h2>
<p>The <code>interval</code> parameter can have the following values:</p>
<table>
<thead>
<tr>
<th>Setting</th>
<th>Description</th>
</tr>
</thead>
<tbody>
<tr>
<td>"yyyy"</td>
<td>Year</td>
</tr>
<tr>
<td>"q"</td>
<td>Quarter</td>
</tr>
<tr>
<td>"m"</td>
<td>Month</td>
</tr>
<tr>
<td>"y"</td>
<td>Day of year</td>
</tr>
<tr>
<td>"d"</td>
<td>Day</td>
</tr>
<tr>
<td>"w"</td>
<td>Weekday</td>
</tr>
<tr>
<td>"ww"</td>
<td>Week of year</td>
</tr>
<tr>
<td>"h"</td>
<td>Hour</td>
</tr>
<tr>
<td>"n"</td>
<td>Minute</td>
</tr>
<tr>
<td>"s"</td>
<td>Second</td>
</tr>
</tbody>
</table>
<h2 id="firstdayofweek-constants"><code>FirstDayOfWeek</code> Constants</h2>
<table>
<thead>
<tr>
<th>Constant</th>
<th>Value</th>
<th>Description</th>
</tr>
</thead>
<tbody>
<tr>
<td>vbUseSystem</td>
<td>0</td>
<td>Use system setting</td>
</tr>
<tr>
<td>vbSunday</td>
<td>1</td>
<td>Sunday (default)</td>
</tr>
<tr>
<td>vbMonday</td>
<td>2</td>
<td>Monday</td>
</tr>
<tr>
<td>vbTuesday</td>
<td>3</td>
<td>Tuesday</td>
</tr>
<tr>
<td>vbWednesday</td>
<td>4</td>
<td>Wednesday</td>
</tr>
<tr>
<td>vbThursday</td>
<td>5</td>
<td>Thursday</td>
</tr>
<tr>
<td>vbFriday</td>
<td>6</td>
<td>Friday</td>
</tr>
<tr>
<td>vbSaturday</td>
<td>7</td>
<td>Saturday</td>
</tr>
</tbody>
</table>
<h2 id="firstweekofyear-constants"><code>FirstWeekOfYear</code> Constants</h2>
<table>
<thead>
<tr>
<th>Constant</th>
<th>Value</th>
<th>Description</th>
</tr>
</thead>
<tbody>
<tr>
<td>vbUseSystem</td>
<td>0</td>
<td>Use system setting</td>
</tr>
<tr>
<td>vbFirstJan1</td>
<td>1</td>
<td>Start with week containing January 1 (default)</td>
</tr>
<tr>
<td>vbFirstFourDays</td>
<td>2</td>
<td>Start with week having at least 4 days in new year</td>
</tr>
<tr>
<td>vbFirstFullWeek</td>
<td>3</td>
<td>Start with first full week of the year</td>
</tr>
</tbody>
</table>
<h2 id="return-value">Return Value</h2>
<p>Returns a <code>Long</code> integer representing the number of intervals between the two dates.
The result is positive if date2 is later than date1, negative if date2 is earlier than date1,
and zero if they are equal.</p>
<h2 id="remarks">Remarks</h2>
<p>The <code>DateDiff</code> function is used to calculate the difference between two dates in the
specified time interval. The function counts the number of interval boundaries crossed
between the two dates.
<strong>Important Characteristics:</strong>
- Returns positive number if date2 > date1 (future date)
- Returns negative number if date2 < date1 (past date)
- Returns zero if date2 = date1 (same date/time)
- Counts interval boundaries, not elapsed time
- For "yyyy", crossing from Dec 31 to Jan 1 counts as 1 year
- For "m", crossing from Jan 31 to Feb 1 counts as 1 month
- For "ww", counts week boundaries (Sunday to Sunday by default)
- Day of year ("y") is equivalent to day ("d")
- Weekday ("w") is equivalent to day ("d")</p>
<h2 id="boundary-counting-vs-elapsed-time">Boundary Counting vs Elapsed Time</h2>
<p><code>DateDiff</code> counts boundaries crossed, not elapsed time:</p>
<pre><code class="language-vbnet">' Year example
DateDiff("yyyy", #12/31/2024#, #1/1/2025#) ' Returns 1 (crossed 1 year boundary)
' But only 1 day elapsed!
' Month example
DateDiff("m", #1/31/2025#, #2/1/2025#) ' Returns 1 (crossed 1 month boundary)
' But only 1 day elapsed!
' Day example (actual elapsed time)
DateDiff("d", #1/1/2025#, #1/31/2025#) ' Returns 30 (30 days elapsed)</code></pre>
<h2 id="examples">Examples</h2>
<h3 id="basic-usage">Basic Usage</h3>
<pre><code class="language-vbnet">' Calculate days between dates
Dim days As Long
days = DateDiff("d", #1/1/2025#, #1/31/2025#)
MsgBox "Days: " & days ' Shows 30
' Calculate months between dates
Dim months As Long
months = DateDiff("m", #1/15/2025#, #6/15/2025#)
MsgBox "Months: " & months ' Shows 5
' Calculate years between dates
Dim years As Long
years = DateDiff("yyyy", #1/1/2000#, #1/1/2025#)
MsgBox "Years: " & years ' Shows 25</code></pre>
<h3 id="age-calculation">Age Calculation</h3>
<pre><code class="language-vbnet">Function CalculateAge(birthDate As Date) As Integer
Dim age As Integer
age = DateDiff("yyyy", birthDate, Date)
' Adjust if birthday hasn't occurred this year
If DateSerial(Year(Date), Month(birthDate), Day(birthDate)) > Date Then
age = age - 1
End If
CalculateAge = age
End Function</code></pre>
<h3 id="days-untilsince-event">Days Until/Since Event</h3>
<pre><code class="language-vbnet">Function DaysUntilEvent(eventDate As Date) As Long
DaysUntilEvent = DateDiff("d", Date, eventDate)
End Function
' Usage
Dim daysLeft As Long
daysLeft = DaysUntilEvent(#12/25/2025#)
If daysLeft > 0 Then
MsgBox daysLeft & " days until Christmas"
ElseIf daysLeft < 0 Then
MsgBox "Christmas was " & Abs(daysLeft) & " days ago"
Else
MsgBox "Today is Christmas!"
End If</code></pre>
<h2 id="common-patterns">Common Patterns</h2>
<h3 id="elapsed-time-display">Elapsed Time Display</h3>
<pre><code class="language-vbnet">Function FormatElapsedTime(startTime As Date, endTime As Date) As String
Dim hours As Long
Dim minutes As Long
Dim seconds As Long
hours = DateDiff("h", startTime, endTime)
minutes = DateDiff("n", startTime, endTime) Mod 60
seconds = DateDiff("s", startTime, endTime) Mod 60
FormatElapsedTime = hours & ":" & Format(minutes, "00") & ":" & Format(seconds, "00")
End Function</code></pre>
<h3 id="working-days-calculator">Working Days Calculator</h3>
<pre><code class="language-vbnet">Function CountWorkingDays(startDate As Date, endDate As Date) As Long
Dim dayCount As Long
Dim workDays As Long
Dim currentDate As Date
dayCount = DateDiff("d", startDate, endDate)
workDays = 0
For i = 0 To dayCount
currentDate = DateAdd("d", i, startDate)
If Weekday(currentDate) <> vbSaturday And Weekday(currentDate) <> vbSunday Then
workDays = workDays + 1
End If
Next i
CountWorkingDays = workDays
End Function</code></pre>
<h3 id="overdue-indicator">Overdue Indicator</h3>
<pre><code class="language-vbnet">Function GetOverdueDays(dueDate As Date) As Long
Dim days As Long
days = DateDiff("d", dueDate, Date)
If days > 0 Then
GetOverdueDays = days ' Positive = overdue
Else
GetOverdueDays = 0 ' Not overdue
End If
End Function</code></pre>
<h3 id="subscription-status">Subscription Status</h3>
<pre><code class="language-vbnet">Function GetSubscriptionStatus(startDate As Date, endDate As Date) As String
Dim daysRemaining As Long
daysRemaining = DateDiff("d", Date, endDate)
Select Case daysRemaining
Case Is < 0
GetSubscriptionStatus = "Expired"
Case 0 To 7
GetSubscriptionStatus = "Expiring Soon (" & daysRemaining & " days)"
Case 8 To 30
GetSubscriptionStatus = "Active (" & daysRemaining & " days left)"
Case Else
GetSubscriptionStatus = "Active"
End Select
End Function</code></pre>
<h3 id="quarterly-report-period">Quarterly Report Period</h3>
<pre><code class="language-vbnet">Function GetQuartersBetween(startDate As Date, endDate As Date) As Integer
GetQuartersBetween = DateDiff("q", startDate, endDate)
End Function
' Check if in same quarter
Function InSameQuarter(date1 As Date, date2 As Date) As Boolean
InSameQuarter = (DateDiff("q", date1, date2) = 0)
End Function</code></pre>
<h3 id="meeting-interval-tracker">Meeting Interval Tracker</h3>
<pre><code class="language-vbnet">Function WeeksSinceLastMeeting(lastMeeting As Date) As Long
WeeksSinceLastMeeting = DateDiff("ww", lastMeeting, Date)
End Function
Function IsMeetingDue(lastMeeting As Date, interval As Integer) As Boolean
IsMeetingDue = (DateDiff("ww", lastMeeting, Date) >= interval)
End Function</code></pre>
<h3 id="time-tracking">Time Tracking</h3>
<pre><code class="language-vbnet">Sub LogSessionDuration(startTime As Date, endTime As Date)
Dim hours As Long
Dim minutes As Long
hours = DateDiff("h", startTime, endTime)
minutes = DateDiff("n", startTime, endTime) - (hours * 60)
Debug.Print "Session duration: " & hours & "h " & minutes & "m"
End Sub</code></pre>
<h3 id="age-range-categorization">Age Range Categorization</h3>
<pre><code class="language-vbnet">Function GetAgeCategory(birthDate As Date) As String
Dim age As Integer
age = DateDiff("yyyy", birthDate, Date)
' Adjust for birthday not yet occurred
If Month(Date) < Month(birthDate) Or _
(Month(Date) = Month(birthDate) And Day(Date) < Day(birthDate)) Then
age = age - 1
End If
Select Case age
Case 0 To 12
GetAgeCategory = "Child"
Case 13 To 19
GetAgeCategory = "Teenager"
Case 20 To 64
GetAgeCategory = "Adult"
Case Else
GetAgeCategory = "Senior"
End Select
End Function</code></pre>
<h2 id="advanced-usage">Advanced Usage</h2>
<h3 id="complete-time-breakdown">Complete Time Breakdown</h3>
<pre><code class="language-vbnet">Type TimeBreakdown
Years As Long
Months As Long
Days As Long
Hours As Long
Minutes As Long
Seconds As Long
End Type
Function GetDetailedDifference(startDate As Date, endDate As Date) As TimeBreakdown
Dim result As TimeBreakdown
Dim tempDate As Date
' Calculate years
result.Years = DateDiff("yyyy", startDate, endDate)
tempDate = DateAdd("yyyy", result.Years, startDate)
If tempDate > endDate Then
result.Years = result.Years - 1
tempDate = DateAdd("yyyy", result.Years, startDate)
End If
' Calculate months
result.Months = DateDiff("m", tempDate, endDate)
tempDate = DateAdd("m", result.Months, tempDate)
If tempDate > endDate Then
result.Months = result.Months - 1
tempDate = DateAdd("m", result.Months, DateAdd("yyyy", result.Years, startDate))
End If
' Calculate remaining time
result.Days = DateDiff("d", tempDate, endDate)
result.Hours = DateDiff("h", tempDate, endDate) Mod 24
result.Minutes = DateDiff("n", tempDate, endDate) Mod 60
result.Seconds = DateDiff("s", tempDate, endDate) Mod 60
GetDetailedDifference = result
End Function</code></pre>
<h3 id="week-number-with-custom-first-day">Week Number with Custom First Day</h3>
<pre><code class="language-vbnet">Function GetWeekNumber(dateValue As Date, startDay As VbDayOfWeek) As Long
Dim yearStart As Date
yearStart = DateSerial(Year(dateValue), 1, 1)
GetWeekNumber = DateDiff("ww", yearStart, dateValue, startDay, vbFirstFourDays)
End Function
' Usage
Dim weekNum As Long
weekNum = GetWeekNumber(Date, vbMonday) ' ISO week number (Monday start)</code></pre>
<h3 id="performance-timer">Performance Timer</h3>
<pre><code class="language-vbnet">Private m_startTime As Date
Sub StartTimer()
m_startTime = Now
End Sub
Function GetElapsedMilliseconds() As Double
Dim seconds As Long
seconds = DateDiff("s", m_startTime, Now)
' VB6 doesn't support milliseconds directly
' This gives seconds as closest approximation
GetElapsedMilliseconds = seconds * 1000
End Function</code></pre>
<h3 id="date-range-validator">Date Range Validator</h3>
<pre><code class="language-vbnet">Function ValidateDateRange(startDate As Date, endDate As Date, _
maxDays As Long) As Boolean
Dim daysDiff As Long
' Check date order
If startDate > endDate Then
ValidateDateRange = False
Exit Function
End If
' Check range limit
daysDiff = DateDiff("d", startDate, endDate)
ValidateDateRange = (daysDiff <= maxDays)
End Function</code></pre>
<h3 id="fiscal-period-calculator">Fiscal Period Calculator</h3>
<pre><code class="language-vbnet">Function GetFiscalPeriodDifference(date1 As Date, date2 As Date, _
fiscalYearStart As Integer) As Long
' Calculate fiscal months between dates
' fiscalYearStart = month number (e.g., 4 for April)
Dim adjustedDate1 As Date
Dim adjustedDate2 As Date
' Adjust dates to fiscal year basis
adjustedDate1 = DateSerial(Year(date1), Month(date1) - fiscalYearStart + 1, Day(date1))
adjustedDate2 = DateSerial(Year(date2), Month(date2) - fiscalYearStart + 1, Day(date2))
GetFiscalPeriodDifference = DateDiff("m", adjustedDate1, adjustedDate2)
End Function</code></pre>
<h3 id="batch-date-comparison">Batch Date Comparison</h3>
<pre><code class="language-vbnet">Function FindOldestDate(dates() As Date) As Date
Dim i As Integer
Dim oldest As Date
oldest = dates(LBound(dates))
For i = LBound(dates) + 1 To UBound(dates)
If DateDiff("d", dates(i), oldest) > 0 Then
oldest = dates(i)
End If
Next i
FindOldestDate = oldest
End Function</code></pre>
<h2 id="error-handling">Error Handling</h2>
<pre><code class="language-vbnet">Function SafeDateDiff(interval As String, date1 As Variant, _
date2 As Variant) As Variant
On Error GoTo ErrorHandler
' Validate dates
If Not IsDate(date1) Or Not IsDate(date2) Then
SafeDateDiff = Null
Exit Function
End If
' Validate interval
Select Case LCase(interval)
Case "yyyy", "q", "m", "y", "d", "w", "ww", "h", "n", "s"
SafeDateDiff = DateDiff(interval, CDate(date1), CDate(date2))
Case Else
SafeDateDiff = Null
End Select
Exit Function
ErrorHandler:
SafeDateDiff = Null
End Function</code></pre>
<h3 id="common-errors">Common Errors</h3>
<ul>
<li><strong>Error 5</strong> (Invalid procedure call): Invalid interval string</li>
<li><strong>Error 13</strong> (Type mismatch): Non-date values passed as date parameters</li>
<li><strong>Error 6</strong> (Overflow): Result exceeds Long integer range</li>
</ul>
<h2 id="performance-considerations">Performance Considerations</h2>
<ul>
<li><code>DateDiff</code> is very fast for simple interval calculations</li>
<li>Day ("d") calculations are fastest</li>
<li>Month ("m") and year ("yyyy") require more computation</li>
<li>Week calculations depend on <code>FirstDayOfWeek</code> and <code>FirstWeekOfYear</code> parameters</li>
<li>For large datasets, cache <code>DateDiff</code> results when possible</li>
</ul>
<h2 id="best-practices">Best Practices</h2>
<h3 id="use-appropriate-intervals">Use Appropriate Intervals</h3>
<pre><code class="language-vbnet">' Good - Use "d" for exact day count
days = DateDiff("d", startDate, endDate)
' Be careful - "yyyy" counts year boundaries, not elapsed years
years = DateDiff("yyyy", #12/31/2024#, #1/1/2025#) ' Returns 1, but only 1 day!</code></pre>
<h3 id="order-matters">Order Matters</h3>
<pre><code class="language-vbnet">' Positive result - date2 is in future
diff = DateDiff("d", #1/1/2025#, #1/31/2025#) ' Returns 30
' Negative result - date2 is in past
diff = DateDiff("d", #1/31/2025#, #1/1/2025#) ' Returns -30</code></pre>
<h3 id="handle-negative-results">Handle Negative Results</h3>
<pre><code class="language-vbnet">Function GetAbsoluteDaysDifference(date1 As Date, date2 As Date) As Long
GetAbsoluteDaysDifference = Abs(DateDiff("d", date1, date2))
End Function</code></pre>
<h3 id="validate-date-order">Validate Date Order</h3>
<pre><code class="language-vbnet">Function CalculateDuration(startDate As Date, endDate As Date) As Long
If startDate > endDate Then
Err.Raise 5, , "Start date must be before end date"
End If
CalculateDuration = DateDiff("d", startDate, endDate)
End Function</code></pre>
<h2 id="comparison-with-other-functions">Comparison with Other Functions</h2>
<h3 id="datediff-vs-dateadd"><code>DateDiff</code> vs <code>DateAdd</code></h3>
<pre><code class="language-vbnet">' `DateDiff` - Calculate interval between dates (returns Long)
diff = DateDiff("d", #1/1/2025#, #1/31/2025#) ' Returns 30
' `DateAdd` - Add interval to date (returns Date)
newDate = DateAdd("d", 30, #1/1/2025#) ' Returns #1/31/2025#</code></pre>
<h3 id="datediff-vs-subtraction"><code>DateDiff</code> vs Subtraction</h3>
<pre><code class="language-vbnet">' Subtraction gives days as Double
diff = #1/31/2025# - #1/1/2025# ' Returns 30.0
' DateDiff gives days as Long
diff = DateDiff("d", #1/1/2025#, #1/31/2025#) ' Returns 30
' DateDiff supports other intervals
months = DateDiff("m", #1/1/2025#, #6/1/2025#) ' Returns 5</code></pre>
<h2 id="limitations">Limitations</h2>
<ul>
<li>Result must fit in Long integer range (-2,147,483,648 to 2,147,483,647)</li>
<li>Week calculations depend on system or specified first day of week</li>
<li>Counts boundaries crossed, not elapsed time (except for "d", "h", "n", "s")</li>
<li>No built-in support for milliseconds</li>
<li>No built-in support for business day calculations</li>
<li>Cannot directly exclude holidays</li>
</ul>
<h2 id="related-functions">Related Functions</h2>
<ul>
<li><code>DateAdd</code>: Adds a time interval to a date</li>
<li><code>DatePart</code>: Returns a specified part of a date</li>
<li><code>DateSerial</code>: Creates a date from year, month, and day values</li>
<li><code>Year</code>, <code>Month</code>, <code>Day</code>: Extract date components</li>
<li><code>Hour</code>, <code>Minute</code>, <code>Second</code>: Extract time components</li>
<li><code>Weekday</code>: Returns the day of the week</li>
<li><code>Now</code>: Returns current date and time</li>
<li><code>Date</code>: Returns current date</li>
<li><code>Time</code>: Returns current time</li>
</ul>
</article>
<div style="margin-top: 3rem; padding-top: 2rem; border-top: 1px solid var(--border-color);">
<p>
<a href="index.html">← Back to Datetime</a> |
<a href="../index.html">View all functions</a>
</p>
</div>
</main>
<footer>
<div class="container">
<p>© 2024-2026 VB6Parse Contributors. Licensed under the MIT License.</p>
</div>
</footer>
</body>
</html>