<!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 - time - Datetime">
<title>time - 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> / time</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">
<p>VB6 Time Function
The <code>Time</code> function returns a Variant (Date) indicating the current system time.</p>
<h2 id="syntax">Syntax</h2>
<pre><code class="language-vbnet">Time()</code></pre>
<p>or</p>
<pre><code class="language-vbnet">Time</code></pre>
<h2 id="parameters">Parameters</h2>
<p>None. The <code>Time</code> function takes no arguments.</p>
<h2 id="returns">Returns</h2>
<p>Returns a <code>Variant</code> of subtype <code>Date</code> containing the current system time. The date portion is set to zero (December 30, 1899).</p>
<h2 id="remarks">Remarks</h2>
<p>The <code>Time</code> function retrieves the current system time:
- <strong>No arguments</strong>: Called without parentheses or with empty parentheses
- <strong>Date portion</strong>: Always returns date as zero (12/30/1899)
- <strong>Time precision</strong>: Returns time to the nearest second (no milliseconds)
- <strong>System dependent</strong>: Returns time from system clock
- <strong>Time vs Time$</strong>: <code>Time</code> returns Variant (Date), <code>Time$</code> returns String in format "HH:MM:SS"
- <strong>Now function</strong>: Use <code>Now()</code> to get current date and time together
- <strong>Date function</strong>: Use <code>Date()</code> to get current date only
- <strong>Timer function</strong>: Use <code>Timer</code> for elapsed time measurements (returns seconds since midnight)
- <strong>Setting time</strong>: Use <code>Time</code> statement (not function) to set system time
- <strong>24-hour format</strong>: Internal representation is 24-hour, but display depends on system settings</p>
<h3 id="time-vs-related-functions">Time vs Related Functions</h3>
<ul>
<li><code>Time</code> - Returns current time only (date portion is zero)</li>
<li><code>Date</code> - Returns current date only (time portion is midnight)</li>
<li><code>Now</code> - Returns current date and time together</li>
<li><code>Timer</code> - Returns seconds elapsed since midnight as Single</li>
<li><code>Time$</code> - Returns current time as formatted String</li>
</ul>
<h3 id="time-components">Time Components</h3>
<p>Extract time components using:</p>
<pre><code class="language-vbnet">currentHour = Hour(Time) ' 0-23
currentMinute = Minute(Time) ' 0-59
currentSecond = Second(Time) ' 0-59</code></pre>
<h3 id="time-arithmetic">Time Arithmetic</h3>
<pre><code class="language-vbnet">' Add 1 hour to current time
newTime = Time + TimeSerial(1, 0, 0)
' Add 30 minutes to current time
newTime = DateAdd("n", 30, Time)</code></pre>
<h2 id="typical-uses">Typical Uses</h2>
<ol>
<li><strong>Timestamp Logging</strong>: Record when events occur</li>
<li><strong>Time-based Triggers</strong>: Check current time for scheduled operations</li>
<li><strong>Time Display</strong>: Show current time in user interface</li>
<li><strong>Performance Timing</strong>: Measure operation duration (though Timer is better)</li>
<li><strong>Time Validation</strong>: Check if operation is within allowed time window</li>
<li><strong>Time Calculations</strong>: Calculate time differences or future times</li>
<li><strong>Scheduling</strong>: Determine if tasks should run now</li>
<li><strong>Time Formatting</strong>: Create custom time displays</li>
</ol>
<h2 id="basic-examples">Basic Examples</h2>
<h3 id="example-1-display-current-time">Example 1: Display Current Time</h3>
<pre><code class="language-vbnet">Sub ShowCurrentTime()
MsgBox "Current time is: " & Time
End Sub</code></pre>
<h3 id="example-2-log-event-time">Example 2: Log Event Time</h3>
<pre><code class="language-vbnet">Sub LogEvent(eventName As String)
Dim logEntry As String
logEntry = Time & " - " & eventName
Debug.Print logEntry
End Sub</code></pre>
<h3 id="example-3-check-business-hours">Example 3: Check Business Hours</h3>
<pre><code class="language-vbnet">Function IsBusinessHours() As Boolean
Dim currentHour As Integer
currentHour = Hour(Time)
IsBusinessHours = (currentHour >= 9 And currentHour < 17)
End Function</code></pre>
<h3 id="example-4-format-time-display">Example 4: Format Time Display</h3>
<pre><code class="language-vbnet">Function GetFormattedTime() As String
GetFormattedTime = Format$(Time, "hh:mm:ss AM/PM")
End Function</code></pre>
<h2 id="common-patterns">Common Patterns</h2>
<h3 id="pattern-1-get-current-hour">Pattern 1: Get Current Hour</h3>
<pre><code class="language-vbnet">Function GetCurrentHour() As Integer
GetCurrentHour = Hour(Time)
End Function</code></pre>
<h3 id="pattern-2-time-based-greeting">Pattern 2: Time-based Greeting</h3>
<pre><code class="language-vbnet">Function GetGreeting() As String
Dim currentHour As Integer
currentHour = Hour(Time)
Select Case currentHour
Case 0 To 11
GetGreeting = "Good morning"
Case 12 To 17
GetGreeting = "Good afternoon"
Case Else
GetGreeting = "Good evening"
End Select
End Function</code></pre>
<h3 id="pattern-3-create-timestamp">Pattern 3: Create Timestamp</h3>
<pre><code class="language-vbnet">Function CreateTimestamp() As String
CreateTimestamp = Format$(Date, "yyyy-mm-dd") & " " & Format$(Time, "hh:nn:ss")
End Function</code></pre>
<h3 id="pattern-4-check-time-window">Pattern 4: Check Time Window</h3>
<pre><code class="language-vbnet">Function IsWithinTimeWindow(startTime As Date, endTime As Date) As Boolean
Dim currentTime As Date
currentTime = Time
IsWithinTimeWindow = (currentTime >= startTime And currentTime <= endTime)
End Function</code></pre>
<h3 id="pattern-5-add-time-duration">Pattern 5: Add Time Duration</h3>
<pre><code class="language-vbnet">Function AddMinutes(minutes As Integer) As Date
AddMinutes = DateAdd("n", minutes, Time)
End Function</code></pre>
<h3 id="pattern-6-time-until-target">Pattern 6: Time Until Target</h3>
<pre><code class="language-vbnet">Function MinutesUntil(targetTime As Date) As Long
MinutesUntil = DateDiff("n", Time, targetTime)
End Function</code></pre>
<h3 id="pattern-7-round-time-to-nearest-interval">Pattern 7: Round Time to Nearest Interval</h3>
<pre><code class="language-vbnet">Function RoundToNearest15Minutes() As Date
Dim currentTime As Date
Dim minutes As Integer
currentTime = Time
minutes = Minute(currentTime)
minutes = ((minutes + 7) \ 15) * 15
RoundToNearest15Minutes = TimeSerial(Hour(currentTime), minutes, 0)
End Function</code></pre>
<h3 id="pattern-8-compare-times">Pattern 8: Compare Times</h3>
<pre><code class="language-vbnet">Function IsTimeBefore(compareTime As Date) As Boolean
IsTimeBefore = (Time < compareTime)
End Function</code></pre>
<h3 id="pattern-9-get-time-string">Pattern 9: Get Time String</h3>
<pre><code class="language-vbnet">Function GetTimeString() As String
GetTimeString = Format$(Time, "hh:mm:ss")
End Function</code></pre>
<h3 id="pattern-10-calculate-elapsed-time">Pattern 10: Calculate Elapsed Time</h3>
<pre><code class="language-vbnet">Function GetElapsedMinutes(startTime As Date) As Long
GetElapsedMinutes = DateDiff("n", startTime, Time)
End Function</code></pre>
<h2 id="advanced-usage">Advanced Usage</h2>
<h3 id="example-1-time-tracker-class">Example 1: Time Tracker Class</h3>
<pre><code class="language-vbnet">' Class: TimeTracker
' Tracks operation start/end times and durations
Option Explicit
Private m_StartTime As Date
Private m_EndTime As Date
Private m_IsRunning As Boolean
Public Sub StartTracking()
m_StartTime = Time
m_IsRunning = True
End Sub
Public Sub StopTracking()
If Not m_IsRunning Then
Err.Raise 5, , "Tracking not started"
End If
m_EndTime = Time
m_IsRunning = False
End Sub
Public Function GetElapsedMinutes() As Long
If m_IsRunning Then
GetElapsedMinutes = DateDiff("n", m_StartTime, Time)
Else
GetElapsedMinutes = DateDiff("n", m_StartTime, m_EndTime)
End If
End Function
Public Function GetElapsedSeconds() As Long
If m_IsRunning Then
GetElapsedSeconds = DateDiff("s", m_StartTime, Time)
Else
GetElapsedSeconds = DateDiff("s", m_StartTime, m_EndTime)
End If
End Function
Public Function GetFormattedDuration() As String
Dim totalSeconds As Long
Dim hours As Long
Dim minutes As Long
Dim seconds As Long
totalSeconds = GetElapsedSeconds()
hours = totalSeconds \ 3600
minutes = (totalSeconds Mod 3600) \ 60
seconds = totalSeconds Mod 60
GetFormattedDuration = Format$(hours, "00") & ":" & _
Format$(minutes, "00") & ":" & _
Format$(seconds, "00")
End Function
Public Property Get IsRunning() As Boolean
IsRunning = m_IsRunning
End Property</code></pre>
<h3 id="example-2-schedule-manager-module">Example 2: Schedule Manager Module</h3>
<pre><code class="language-vbnet">' Module: ScheduleManager
' Manages time-based scheduling and windows
Option Explicit
Public Function IsWithinSchedule(scheduleStart As Date, scheduleEnd As Date) As Boolean
Dim currentTime As Date
currentTime = Time
' Handle overnight schedules (e.g., 10 PM to 6 AM)
If scheduleStart > scheduleEnd Then
IsWithinSchedule = (currentTime >= scheduleStart Or currentTime <= scheduleEnd)
Else
IsWithinSchedule = (currentTime >= scheduleStart And currentTime <= scheduleEnd)
End If
End Function
Public Function GetNextScheduledTime(targetTime As Date) As Date
Dim currentTime As Date
currentTime = Time
If currentTime < targetTime Then
' Target time is later today
GetNextScheduledTime = Date + targetTime
Else
' Target time is tomorrow
GetNextScheduledTime = Date + 1 + targetTime
End If
End Function
Public Function MinutesUntilSchedule(scheduleTime As Date) As Long
Dim currentTime As Date
Dim targetDateTime As Date
currentTime = Time
If currentTime < scheduleTime Then
' Later today
targetDateTime = Date + scheduleTime
Else
' Tomorrow
targetDateTime = Date + 1 + scheduleTime
End If
MinutesUntilSchedule = DateDiff("n", Now, targetDateTime)
End Function
Public Function FormatTimeRemaining(targetTime As Date) As String
Dim minutesLeft As Long
Dim hours As Long
Dim minutes As Long
minutesLeft = MinutesUntilSchedule(targetTime)
If minutesLeft < 0 Then
FormatTimeRemaining = "Overdue"
Exit Function
End If
hours = minutesLeft \ 60
minutes = minutesLeft Mod 60
If hours > 0 Then
FormatTimeRemaining = hours & "h " & minutes & "m remaining"
Else
FormatTimeRemaining = minutes & "m remaining"
End If
End Function</code></pre>
<h3 id="example-3-time-logger-class">Example 3: Time Logger Class</h3>
<pre><code class="language-vbnet">' Class: TimeLogger
' Logs timestamped events
Option Explicit
Private m_LogEntries As Collection
Private Sub Class_Initialize()
Set m_LogEntries = New Collection
End Sub
Public Sub LogEvent(eventDescription As String)
Dim logEntry As String
logEntry = Format$(Time, "hh:mm:ss") & " - " & eventDescription
m_LogEntries.Add logEntry
End Sub
Public Sub LogEventWithDetails(eventName As String, details As String)
Dim logEntry As String
logEntry = Format$(Time, "hh:mm:ss") & " - " & eventName & ": " & details
m_LogEntries.Add logEntry
End Sub
Public Function GetLogEntries() As String
Dim result As String
Dim entry As Variant
result = "Event Log:" & vbCrLf
result = result & String$(50, "=") & vbCrLf
For Each entry In m_LogEntries
result = result & entry & vbCrLf
Next entry
GetLogEntries = result
End Function
Public Sub ClearLog()
Set m_LogEntries = New Collection
End Sub
Public Property Get EntryCount() As Long
EntryCount = m_LogEntries.Count
End Property
Public Function ExportToFile(filename As String) As Boolean
On Error GoTo ErrorHandler
Dim fileNum As Integer
Dim entry As Variant
fileNum = FreeFile
Open filename For Output As #fileNum
Print #fileNum, "Event Log - " & Format$(Date, "yyyy-mm-dd")
Print #fileNum, String$(50, "=")
For Each entry In m_LogEntries
Print #fileNum, entry
Next entry
Close #fileNum
ExportToFile = True
Exit Function
ErrorHandler:
ExportToFile = False
If fileNum > 0 Then Close #fileNum
End Function</code></pre>
<h3 id="example-4-business-hours-validator-module">Example 4: Business Hours Validator Module</h3>
<pre><code class="language-vbnet">' Module: BusinessHoursValidator
' Validates and manages business hours
Option Explicit
Private m_BusinessStart As Date
Private m_BusinessEnd As Date
Private m_LunchStart As Date
Private m_LunchEnd As Date
Public Sub Initialize(businessStart As Date, businessEnd As Date, _
Optional lunchStart As Variant, Optional lunchEnd As Variant)
m_BusinessStart = businessStart
m_BusinessEnd = businessEnd
If Not IsMissing(lunchStart) Then m_LunchStart = lunchStart
If Not IsMissing(lunchEnd) Then m_LunchEnd = lunchEnd
End Sub
Public Function IsBusinessHours() As Boolean
Dim currentTime As Date
currentTime = Time
' Check if within business hours
If currentTime < m_BusinessStart Or currentTime >= m_BusinessEnd Then
IsBusinessHours = False
Exit Function
End If
' Check if during lunch (if configured)
If m_LunchStart > 0 And m_LunchEnd > 0 Then
If currentTime >= m_LunchStart And currentTime < m_LunchEnd Then
IsBusinessHours = False
Exit Function
End If
End If
IsBusinessHours = True
End Function
Public Function GetBusinessHoursStatus() As String
Dim currentTime As Date
currentTime = Time
If currentTime < m_BusinessStart Then
GetBusinessHoursStatus = "Before business hours (opens at " & _
Format$(m_BusinessStart, "h:mm AM/PM") & ")"
ElseIf currentTime >= m_BusinessEnd Then
GetBusinessHoursStatus = "After business hours (closed at " & _
Format$(m_BusinessEnd, "h:mm AM/PM") & ")"
ElseIf m_LunchStart > 0 And currentTime >= m_LunchStart And currentTime < m_LunchEnd Then
GetBusinessHoursStatus = "Lunch break (returns at " & _
Format$(m_LunchEnd, "h:mm AM/PM") & ")"
Else
GetBusinessHoursStatus = "Open for business"
End If
End Function
Public Function MinutesUntilOpen() As Long
Dim currentTime As Date
currentTime = Time
If currentTime < m_BusinessStart Then
MinutesUntilOpen = DateDiff("n", currentTime, m_BusinessStart)
Else
' Next business day
Dim nextOpen As Date
nextOpen = DateAdd("d", 1, Date) + m_BusinessStart
MinutesUntilOpen = DateDiff("n", Now, nextOpen)
End If
End Function
Public Function MinutesUntilClose() As Long
Dim currentTime As Date
currentTime = Time
If currentTime >= m_BusinessEnd Then
MinutesUntilClose = 0
Else
MinutesUntilClose = DateDiff("n", currentTime, m_BusinessEnd)
End If
End Function</code></pre>
<h2 id="error-handling">Error Handling</h2>
<p>The <code>Time</code> function typically does not raise errors under normal circumstances:
- <strong>No parameters</strong>: Cannot have parameter errors
- <strong>System dependent</strong>: Relies on system clock being set correctly
- <strong>Always succeeds</strong>: Returns current time from system</p>
<h2 id="performance-notes">Performance Notes</h2>
<ul>
<li>Very fast operation - direct system call</li>
<li>Negligible performance impact</li>
<li>Can be called repeatedly without concern</li>
<li>For high-precision timing, use <code>Timer</code> function instead</li>
<li>Time resolution limited to one second</li>
</ul>
<h2 id="best-practices">Best Practices</h2>
<ol>
<li><strong>Use Now for timestamps</strong> if you need both date and time</li>
<li><strong>Use Timer for performance</strong> measurements (higher precision)</li>
<li><strong>Cache Time value</strong> if using multiple times in tight loop</li>
<li><strong>Use Format$</strong> to display time in specific format</li>
<li><strong>Consider time zones</strong> for distributed applications</li>
<li><strong>Validate system time</strong> is set correctly if critical</li>
<li><strong>Use <code>TimeSerial</code></strong> to create specific time values for comparison</li>
<li><strong>Handle overnight periods</strong> carefully (when start > end time)</li>
<li><strong>Store as Date type</strong> not String for calculations</li>
<li><strong>Document time format</strong> assumptions in code comments</li>
</ol>
<h2 id="comparison-table">Comparison Table</h2>
<table>
<thead>
<tr>
<th>Function</th>
<th>Returns</th>
<th>Includes Date</th>
<th>Includes Time</th>
<th>Precision</th>
</tr>
</thead>
<tbody>
<tr>
<td><code>Time</code></td>
<td>Variant (Date)</td>
<td>No (zero date)</td>
<td>Yes</td>
<td>1 second</td>
</tr>
<tr>
<td><code>Date</code></td>
<td>Variant (Date)</td>
<td>Yes</td>
<td>No (midnight)</td>
<td>1 day</td>
</tr>
<tr>
<td><code>Now</code></td>
<td>Variant (Date)</td>
<td>Yes</td>
<td>Yes</td>
<td>1 second</td>
</tr>
<tr>
<td><code>Timer</code></td>
<td>Single</td>
<td>No</td>
<td>Yes (seconds since midnight)</td>
<td>High</td>
</tr>
<tr>
<td><code>Time$</code></td>
<td>String</td>
<td>No</td>
<td>Yes</td>
<td>1 second</td>
</tr>
</tbody>
</table>
<h2 id="platform-notes">Platform Notes</h2>
<ul>
<li>Available in VB6, VBA, and <code>VBScript</code></li>
<li>Consistent behavior across platforms</li>
<li>Returns time based on system clock</li>
<li>Time format display depends on regional settings</li>
<li>Internal representation is numeric (fraction of a day)</li>
<li>Date portion always 12/30/1899 (zero date)</li>
</ul>
<h2 id="limitations">Limitations</h2>
<ul>
<li>No millisecond precision (use Timer for better precision)</li>
<li>Cannot get time from different time zone</li>
<li>No built-in UTC time support</li>
<li>Cannot specify which clock source to use</li>
<li>Display format depends on system locale settings</li>
<li>Cannot return time as numeric value directly (use <code>CDbl</code> or cast)</li>
<li>No built-in support for daylight saving time handling</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>