<!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 - datepart - Datetime">
<title>datepart - 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> / datepart</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="datepart-function">DatePart Function</h1>
<p>Returns a <code>Variant</code> (<code>Integer</code>) containing the specified part of a given date.</p>
<h2 id="syntax">Syntax</h2>
<pre><code class="language-vbnet">DatePart(interval, date[, 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 return.
See the Interval Settings section for valid values.</li>
<li><strong>date</strong>: Required. <code>Variant</code> (<code>Date</code>) value that you want to evaluate.</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>
<th>Return Range</th>
</tr>
</thead>
<tbody>
<tr>
<td>"yyyy"</td>
<td>Year</td>
<td>100-9999</td>
</tr>
<tr>
<td>"q"</td>
<td>Quarter</td>
<td>1-4</td>
</tr>
<tr>
<td>"m"</td>
<td>Month</td>
<td>1-12</td>
</tr>
<tr>
<td>"y"</td>
<td>Day of year</td>
<td>1-366</td>
</tr>
<tr>
<td>"d"</td>
<td>Day</td>
<td>1-31</td>
</tr>
<tr>
<td>"w"</td>
<td>Weekday</td>
<td>1-7 (Sunday=1)</td>
</tr>
<tr>
<td>"ww"</td>
<td>Week of year</td>
<td>1-53</td>
</tr>
<tr>
<td>"h"</td>
<td>Hour</td>
<td>0-23</td>
</tr>
<tr>
<td>"n"</td>
<td>Minute</td>
<td>0-59</td>
</tr>
<tr>
<td>"s"</td>
<td>Second</td>
<td>0-59</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 an <code>Integer</code> representing the specified part of the date. Returns <code>Null</code> if the date is <code>Null</code>.</p>
<h2 id="remarks">Remarks</h2>
<p>The <code>DatePart</code> function is used to extract a specific component from a date value.
It's particularly useful for date-based calculations, filtering, and grouping operations.
<strong>Important Characteristics:</strong>
- More flexible than <code>Year()</code>, <code>Month()</code>, or <code>Day()</code> functions.
- Can extract quarter, week, and day of year.
- Weekday numbering depends on <code>firstdayofweek</code> parameter.
- Week numbering depends on <code>firstweekofyear</code> parameter.
- Hours use 24-hour format (0-23).
- Sunday is 1 by default for weekday ("w").
- Compatible with SQL Server's <code>DATEPART</code> function</p>
<h2 id="equivalent-simple-functions">Equivalent Simple Functions</h2>
<p>Some intervals have equivalent dedicated functions:
- <code>DatePart("yyyy", date)</code> = <code>Year(date)</code>
- <code>DatePart("m", date)</code> = <code>Month(date)</code>
- <code>DatePart("d", date)</code> = <code>Day(date)</code>
- <code>DatePart("w", date)</code> = <code>Weekday(date)</code>
- <code>DatePart("h", date)</code> = <code>Hour(date)</code>
- <code>DatePart("n", date)</code> = <code>Minute(date)</code>
- <code>DatePart("s", date)</code> = <code>Second(date)</code></p>
<h2 id="examples">Examples</h2>
<h3 id="basic-usage">Basic Usage</h3>
<pre><code class="language-vbnet">Dim testDate As Date
testDate = #3/15/2025 14:30:45#
' Extract various parts
MsgBox "Year: " & DatePart("yyyy", testDate) ' 2025
MsgBox "Quarter: " & DatePart("q", testDate) ' 1
MsgBox "Month: " & DatePart("m", testDate) ' 3
MsgBox "Day: " & DatePart("d", testDate) ' 15
MsgBox "Day of Year: " & DatePart("y", testDate) ' 74
MsgBox "Weekday: " & DatePart("w", testDate) ' Varies by day
MsgBox "Week: " & DatePart("ww", testDate) ' Week number
MsgBox "Hour: " & DatePart("h", testDate) ' 14
MsgBox "Minute: " & DatePart("n", testDate) ' 30
MsgBox "Second: " & DatePart("s", testDate) ' 45</code></pre>
<h3 id="quarter-calculation">Quarter Calculation</h3>
<pre><code class="language-vbnet">Function GetQuarter(dateValue As Date) As Integer
GetQuarter = DatePart("q", dateValue)
End Function
' Usage
Dim currentQuarter As Integer
currentQuarter = GetQuarter(Date)
MsgBox "We are in Q" & currentQuarter</code></pre>
<h3 id="week-number">Week Number</h3>
<pre><code class="language-vbnet">Function GetWeekNumber(dateValue As Date) As Integer
' ISO week number (Monday start, 4-day rule)
GetWeekNumber = DatePart("ww", dateValue, vbMonday, vbFirstFourDays)
End Function</code></pre>
<h2 id="common-patterns">Common Patterns</h2>
<h3 id="fiscal-quarter-determination">Fiscal Quarter Determination</h3>
<pre><code class="language-vbnet">Function GetFiscalQuarter(dateValue As Date, fiscalYearStart As Integer) As Integer
' fiscalYearStart is the month number (e.g., 4 for April)
Dim currentMonth As Integer
Dim adjustedMonth As Integer
currentMonth = DatePart("m", dateValue)
adjustedMonth = currentMonth - fiscalYearStart + 1
If adjustedMonth <= 0 Then
adjustedMonth = adjustedMonth + 12
End If
GetFiscalQuarter = Int((adjustedMonth - 1) / 3) + 1
End Function</code></pre>
<h3 id="group-by-time-period">Group By Time Period</h3>
<pre><code class="language-vbnet">Function GroupByPeriod(dateValue As Date, period As String) As String
Select Case LCase(period)
Case "year"
GroupByPeriod = CStr(DatePart("yyyy", dateValue))
Case "quarter"
GroupByPeriod = DatePart("yyyy", dateValue) & "-Q" & DatePart("q", dateValue)
Case "month"
GroupByPeriod = DatePart("yyyy", dateValue) & "-" & Format(DatePart("m", dateValue), "00")
Case "week"
GroupByPeriod = DatePart("yyyy", dateValue) & "-W" & Format(DatePart("ww", dateValue), "00")
Case Else
GroupByPeriod = Format(dateValue, "yyyy-mm-dd")
End Select
End Function</code></pre>
<h3 id="day-name-from-weekday">Day Name from Weekday</h3>
<pre><code class="language-vbnet">Function GetDayName(dateValue As Date) As String
Select Case DatePart("w", dateValue)
Case 1: GetDayName = "Sunday"
Case 2: GetDayName = "Monday"
Case 3: GetDayName = "Tuesday"
Case 4: GetDayName = "Wednesday"
Case 5: GetDayName = "Thursday"
Case 6: GetDayName = "Friday"
Case 7: GetDayName = "Saturday"
End Select
End Function</code></pre>
<h3 id="time-of-day-category">Time of Day Category</h3>
<pre><code class="language-vbnet">Function GetTimeOfDay(dateValue As Date) As String
Dim hour As Integer
hour = DatePart("h", dateValue)
Select Case hour
Case 0 To 5
GetTimeOfDay = "Night"
Case 6 To 11
GetTimeOfDay = "Morning"
Case 12 To 17
GetTimeOfDay = "Afternoon"
Case 18 To 23
GetTimeOfDay = "Evening"
End Select
End Function</code></pre>
<h3 id="business-hour-check">Business Hour Check</h3>
<pre><code class="language-vbnet">Function IsBusinessHours(checkTime As Date) As Boolean
Dim hour As Integer
Dim weekday As Integer
hour = DatePart("h", checkTime)
weekday = DatePart("w", checkTime)
' Monday-Friday, 9 AM - 5 PM
If weekday >= 2 And weekday <= 6 Then ' Mon-Fri
If hour >= 9 And hour < 17 Then
IsBusinessHours = True
End If
End If
End Function</code></pre>
<h3 id="month-name-lookup">Month Name Lookup</h3>
<pre><code class="language-vbnet">Function GetMonthName(dateValue As Date) As String
Dim monthNames As Variant
Dim monthNum As Integer
monthNames = Array("January", "February", "March", "April", "May", "June", _
"July", "August", "September", "October", "November", "December")
monthNum = DatePart("m", dateValue)
GetMonthName = monthNames(monthNum - 1)
End Function</code></pre>
<h3 id="quarter-end-date">Quarter End Date</h3>
<pre><code class="language-vbnet">Function GetQuarterEnd(dateValue As Date) As Date
Dim quarter As Integer
Dim year As Integer
Dim endMonth As Integer
quarter = DatePart("q", dateValue)
year = DatePart("yyyy", dateValue)
endMonth = quarter * 3
GetQuarterEnd = DateSerial(year, endMonth + 1, 0) ' Last day of quarter
End Function</code></pre>
<h3 id="data-binning-by-hour">Data Binning by Hour</h3>
<pre><code class="language-vbnet">Function GetHourBucket(timestamp As Date) As String
Dim hour As Integer
hour = DatePart("h", timestamp)
GetHourBucket = Format(hour, "00") & ":00"
End Function
' Use for grouping log entries
Sub AnalyzeLogs()
Dim entry As Date
Dim bucket As String
For Each entry In logEntries
bucket = GetHourBucket(entry)
hourCounts(bucket) = hourCounts(bucket) + 1
Next
End Sub</code></pre>
<h2 id="advanced-usage">Advanced Usage</h2>
<h3 id="iso-8601-week-number">ISO 8601 Week Number</h3>
<pre><code class="language-vbnet">Function GetISOWeekNumber(dateValue As Date) As Integer
' ISO 8601 week number: Monday start, 4-day rule
GetISOWeekNumber = DatePart("ww", dateValue, vbMonday, vbFirstFourDays)
End Function
Function GetISOYear(dateValue As Date) As Integer
' Year for ISO week (may differ from calendar year)
Dim weekNum As Integer
Dim month As Integer
weekNum = GetISOWeekNumber(dateValue)
month = DatePart("m", dateValue)
If month = 1 And weekNum > 51 Then
GetISOYear = DatePart("yyyy", dateValue) - 1
ElseIf month = 12 And weekNum = 1 Then
GetISOYear = DatePart("yyyy", dateValue) + 1
Else
GetISOYear = DatePart("yyyy", dateValue)
End If
End Function</code></pre>
<h3 id="dynamic-date-grouping">Dynamic Date Grouping</h3>
<pre><code class="language-vbnet">Function GetDateKey(dateValue As Date, granularity As String) As String
Dim year As Integer
Dim month As Integer
Dim day As Integer
Dim week As Integer
Dim quarter As Integer
year = DatePart("yyyy", dateValue)
Select Case LCase(granularity)
Case "year"
GetDateKey = CStr(year)
Case "quarter"
quarter = DatePart("q", dateValue)
GetDateKey = year & "Q" & quarter
Case "month"
month = DatePart("m", dateValue)
GetDateKey = year & Format(month, "00")
Case "week"
week = DatePart("ww", dateValue, vbMonday)
GetDateKey = year & "W" & Format(week, "00")
Case "day"
month = DatePart("m", dateValue)
day = DatePart("d", dateValue)
GetDateKey = year & Format(month, "00") & Format(day, "00")
Case Else
GetDateKey = Format(dateValue, "yyyymmdd")
End Select
End Function</code></pre>
<h3 id="custom-calendar-system">Custom Calendar System</h3>
<pre><code class="language-vbnet">Type CustomCalendar
Year As Integer
Period As Integer
Week As Integer
Day As Integer
End Type
Function ConvertToCustomCalendar(dateValue As Date) As CustomCalendar
Dim cal As CustomCalendar
Dim yearStart As Date
Dim dayOfYear As Integer
cal.Year = DatePart("yyyy", dateValue)
' 13 periods of 4 weeks each
yearStart = DateSerial(cal.Year, 1, 1)
dayOfYear = DatePart("y", dateValue)
cal.Week = Int((dayOfYear - 1) / 7) + 1
cal.Period = Int((cal.Week - 1) / 4) + 1
cal.Day = DatePart("w", dateValue, vbMonday)
ConvertToCustomCalendar = cal
End Function</code></pre>
<h3 id="time-series-aggregation">Time Series Aggregation</h3>
<pre><code class="language-vbnet">Function AggregateByInterval(dates() As Date, values() As Double, _
interval As String) As Collection
Dim results As New Collection
Dim i As Long
Dim key As String
Dim total As Double
Dim count As Long
For i = LBound(dates) To UBound(dates)
key = GetDateKey(dates(i), interval)
On Error Resume Next
total = results(key)
If Err.Number <> 0 Then
results.Add values(i), key
Else
results.Remove key
results.Add total + values(i), key
End If
On Error GoTo 0
Next i
Set AggregateByInterval = results
End Function</code></pre>
<h3 id="shift-schedule-detector">Shift Schedule Detector</h3>
<pre><code class="language-vbnet">Function GetShift(timestamp As Date) As String
Dim hour As Integer
Dim weekday As Integer
hour = DatePart("h", timestamp)
weekday = DatePart("w", timestamp)
' Weekend check
If weekday = 1 Or weekday = 7 Then
GetShift = "Weekend"
Exit Function
End If
' Shift determination
Select Case hour
Case 6 To 13
GetShift = "Morning Shift"
Case 14 To 21
GetShift = "Afternoon Shift"
Case Else
GetShift = "Night Shift"
End Select
End Function</code></pre>
<h3 id="calendar-week-display">Calendar Week Display</h3>
<pre><code class="language-vbnet">Function FormatCalendarWeek(dateValue As Date, Optional useISO As Boolean = False) As String
Dim year As Integer
Dim week As Integer
If useISO Then
year = GetISOYear(dateValue)
week = GetISOWeekNumber(dateValue)
Else
year = DatePart("yyyy", dateValue)
week = DatePart("ww", dateValue)
End If
FormatCalendarWeek = year & "-W" & Format(week, "00")
End Function</code></pre>
<h2 id="error-handling">Error Handling</h2>
<pre><code class="language-vbnet">Function SafeDatePart(interval As String, dateValue As Variant) As Variant
On Error GoTo ErrorHandler
' Validate date
If Not IsDate(dateValue) Then
SafeDatePart = Null
Exit Function
End If
' Validate interval
Select Case LCase(interval)
Case "yyyy", "q", "m", "y", "d", "w", "ww", "h", "n", "s"
SafeDatePart = DatePart(interval, CDate(dateValue))
Case Else
SafeDatePart = Null
End Select
Exit Function
ErrorHandler:
SafeDatePart = 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 value passed as date parameter</li>
</ul>
<h2 id="performance-considerations">Performance Considerations</h2>
<ul>
<li><code>DatePart</code> is efficient for single extractions</li>
<li>For multiple parts from same date, consider using dedicated functions:</li>
</ul>
<pre><code class="language-vbnet"> ' Less efficient
y = DatePart("yyyy", d)
m = DatePart("m", d)
d = DatePart("d", d)
' More efficient
y = Year(d)
m = Month(d)
d = Day(d)
```
- Week calculations are more expensive than other intervals
- Cache results when processing large datasets
## Best Practices
### Use Named Constants</code></pre>
<p>vb
' Define interval constants
Const INTERVAL_YEAR As String = "yyyy"
Const INTERVAL_QUARTER As String = "q"
Const INTERVAL_MONTH As String = "m"
Const INTERVAL_WEEK As String = "ww"
' Use in code
quarter = DatePart(INTERVAL_QUARTER, Date)</p>
<pre><code>### Prefer Specific Functions for Simple Cases</code></pre>
<p>vb
' Good - Use specific function
y = Year(someDate)
' Less clear - Using DatePart
y = DatePart("yyyy", someDate)</p>
<pre><code>### Be Aware of Weekday Numbering</code></pre>
<p>vb
' Default: Sunday = 1
day = DatePart("w", Date)
' Explicit: Monday = 1
day = DatePart("w", Date, vbMonday)</p>
<pre><code>## Comparison with Other Functions
### `DatePart` vs Dedicated Functions</code></pre>
<p>vb
' DatePart - Flexible, supports all intervals
quarter = DatePart("q", Date)
dayOfYear = DatePart("y", Date)
' Dedicated - Simpler, more readable for common cases
year = Year(Date)
month = Month(Date)
day = Day(Date)
weekday = Weekday(Date)
```</p>
<h2 id="limitations">Limitations</h2>
<ul>
<li>No millisecond support</li>
<li>Week numbering can be confusing with different standards (ISO vs US)</li>
<li>Quarter calculation doesn't support fiscal quarters directly</li>
<li>No built-in locale-aware day/month names</li>
<li><code>FirstWeekOfYear</code> affects week numbering interpretation</li>
</ul>
<h2 id="related-functions">Related Functions</h2>
<ul>
<li><code>Year</code>: Returns the year part of a date</li>
<li><code>Month</code>: Returns the month part of a date</li>
<li><code>Day</code>: Returns the day part of a date</li>
<li><code>Weekday</code>: Returns the day of the week</li>
<li><code>Hour</code>: Returns the hour part of a time</li>
<li><code>Minute</code>: Returns the minute part of a time</li>
<li><code>Second</code>: Returns the second part of a time</li>
<li><code>DateAdd</code>: Adds a time interval to a date</li>
<li><code>DateDiff</code>: Returns the difference between two dates</li>
<li><code>DateSerial</code>: Creates a date from year, month, and day values</li>
<li><code>Format</code>: Formats a date as a string (alternative for custom formatting)</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>