VB6Parse / Library / Datetime / second

VB6 Library Reference

Second Function

Returns an Integer specifying a whole number between 0 and 59, inclusive, representing the second of the minute.

Syntax

Second(time)

Parameters

Return Value

Returns an Integer between 0 and 59 representing the second of the minute.

Remarks

The Second function extracts the seconds component from a time value. It is commonly used for time parsing, logging, and time-based calculations. Important Notes: - Returns 0-59 (60 seconds in a minute) - If time contains Null, Second returns Null - If time is not a valid time, runtime error occurs (Error 13: Type mismatch) - Only the time portion is used; date portion is ignored - Accepts Date/Time values, numeric values, and valid time strings Valid Input Examples: - Date/Time values: Now, Time, Date - Time strings: "3:45:30 PM", "15:45:30" - Numeric values representing dates: 0.5 (noon), 0.75 (6 PM) - Combined date/time: #1/1/2000 3:45:30 PM#

Typical Uses

  1. Time Parsing: Extract seconds from time values
  2. Logging: Record precise timestamps
  3. Time Calculations: Compute time differences
  4. Scheduling: Check if task should run at specific second
  5. Animation: Time-based animations at second intervals
  6. Performance Timing: Measure elapsed seconds
  7. Data Validation: Verify time components
  8. Report Generation: Format time displays

Basic Examples

Example 1: Get Current Second

Dim currentSecond As Integer
currentSecond = Second(Now)  ' Returns 0-59

Example 2: Parse Time String

Dim timeStr As String
Dim sec As Integer
timeStr = "3:45:30 PM"
sec = Second(timeStr)  ' Returns 30

Example 3: Check Specific Second

If Second(Now) = 0 Then
    MsgBox "New minute started!"
End If

Example 4: Extract from Date/Time

Dim dt As Date
Dim seconds As Integer
dt = #1/15/2000 10:30:45 AM#
seconds = Second(dt)  ' Returns 45

Common Patterns

Pattern 1: GetTimeSeconds

Function GetTimeSeconds(timeValue As Variant) As Integer
    ' Safely get seconds from time value
    On Error Resume Next
    GetTimeSeconds = Second(timeValue)
    If Err.Number <> 0 Then
        GetTimeSeconds = 0
    End If
    On Error GoTo 0
End Function

Pattern 2: FormatTimeWithSeconds

Function FormatTimeWithSeconds(timeValue As Date) As String
    ' Format time as HH:MM:SS
    Dim h As Integer, m As Integer, s As Integer
    h = Hour(timeValue)
    m = Minute(timeValue)
    s = Second(timeValue)
    FormatTimeWithSeconds = Format(h, "00") & ":" & _
                           Format(m, "00") & ":" & _
                           Format(s, "00")
End Function

Pattern 3: IsAtSecondInterval

Function IsAtSecondInterval(timeValue As Date, interval As Integer) As Boolean
    ' Check if time is at a specific second interval
    ' e.g., IsAtSecondInterval(Now, 15) returns True at :00, :15, :30, :45
    IsAtSecondInterval = (Second(timeValue) Mod interval = 0)
End Function

Pattern 4: GetElapsedSeconds

Function GetElapsedSeconds(startTime As Date, endTime As Date) As Long
    ' Get total elapsed seconds between two times
    GetElapsedSeconds = DateDiff("s", startTime, endTime)
End Function

Pattern 5: SetSeconds

Function SetSeconds(timeValue As Date, newSeconds As Integer) As Date
    ' Set the seconds component of a time value
    Dim h As Integer, m As Integer
    h = Hour(timeValue)
    m = Minute(timeValue)
    SetSeconds = TimeSerial(h, m, newSeconds)
End Function

Pattern 6: RoundToNearestMinute

Function RoundToNearestMinute(timeValue As Date) As Date
    ' Round time to nearest minute based on seconds
    Dim h As Integer, m As Integer, s As Integer
    h = Hour(timeValue)
    m = Minute(timeValue)
    s = Second(timeValue)
    If s >= 30 Then
        m = m + 1
        If m = 60 Then
            m = 0
            h = h + 1
            If h = 24 Then h = 0
        End If
    End If
    RoundToNearestMinute = TimeSerial(h, m, 0)
End Function

Pattern 7: CompareTimeToSecond

Function CompareTimeToSecond(time1 As Date, time2 As Date) As Boolean
    ' Compare times to the second (ignore milliseconds)
    Dim h1 As Integer, m1 As Integer, s1 As Integer
    Dim h2 As Integer, m2 As Integer, s2 As Integer
    h1 = Hour(time1): m1 = Minute(time1): s1 = Second(time1)
    h2 = Hour(time2): m2 = Minute(time2): s2 = Second(time2)
    CompareTimeToSecond = (h1 = h2 And m1 = m2 And s1 = s2)
End Function

Pattern 8: ValidateTimeSeconds

Function ValidateTimeSeconds(timeValue As Variant) As Boolean
    ' Validate that seconds are in valid range
    On Error Resume Next
    Dim s As Integer
    s = Second(timeValue)
    If Err.Number <> 0 Then
        ValidateTimeSeconds = False
    Else
        ValidateTimeSeconds = (s >= 0 And s <= 59)
    End If
    On Error GoTo 0
End Function

Pattern 9: GetSecondsUntilMinute

Function GetSecondsUntilMinute(Optional timeValue As Date) As Integer
    ' Get seconds remaining until next minute
    Dim currentTime As Date
    If timeValue = 0 Then
        currentTime = Now
    Else
        currentTime = timeValue
    End If
    GetSecondsUntilMinute = 60 - Second(currentTime)
End Function

Pattern 10: ParseTimeComponents

Sub ParseTimeComponents(timeValue As Date, hours As Integer, _
                       minutes As Integer, seconds As Integer)
    ' Parse time into separate components
    hours = Hour(timeValue)
    minutes = Minute(timeValue)
    seconds = Second(timeValue)
End Sub

Advanced Usage

Example 1: Precise Timer Class

' High-precision timer for performance measurement
Class PreciseTimer
    Private m_startTime As Date
    Private m_running As Boolean
    Public Sub Start()
        m_startTime = Now
        m_running = True
    End Sub
    Public Sub Stop()
        m_running = False
    End Sub
    Public Function GetElapsedSeconds() As Long
        ' Get elapsed seconds
        Dim endTime As Date
        If m_running Then
            endTime = Now
        Else
            endTime = m_startTime
        End If
        GetElapsedSeconds = DateDiff("s", m_startTime, endTime)
    End Function
    Public Function GetElapsedTime() As String
        ' Get formatted elapsed time
        Dim elapsed As Long
        Dim hours As Long, minutes As Long, seconds As Long
        elapsed = GetElapsedSeconds()
        hours = elapsed \ 3600
        minutes = (elapsed Mod 3600) \ 60
        seconds = elapsed Mod 60
        GetElapsedTime = Format(hours, "00") & ":" & _
                        Format(minutes, "00") & ":" & _
                        Format(seconds, "00")
    End Function
    Public Function GetCurrentSecond() As Integer
        ' Get current second of running timer
        If m_running Then
            GetCurrentSecond = Second(Now)
        Else
            GetCurrentSecond = Second(m_startTime)
        End If
    End Function
    Public Sub Reset()
        m_startTime = Now
        m_running = False
    End Sub
    Public Function IsRunning() As Boolean
        IsRunning = m_running
    End Function
End Class

Example 2: Time Logger Module

' Log events with precise timestamps
Module TimeLogger
    Private Type LogEntry
        Timestamp As Date
        Message As String
        Second As Integer
    End Type
    Private m_logEntries() As LogEntry
    Private m_count As Integer
    Public Sub InitializeLog()
        m_count = 0
        ReDim m_logEntries(0 To 999)
    End Sub
    Public Sub LogEvent(message As String, Optional timeValue As Date)
        Dim entry As LogEntry
        Dim logTime As Date
        If m_count > UBound(m_logEntries) Then
            ReDim Preserve m_logEntries(0 To UBound(m_logEntries) + 1000)
        End If
        If timeValue = 0 Then
            logTime = Now
        Else
            logTime = timeValue
        End If
        entry.Timestamp = logTime
        entry.Message = message
        entry.Second = Second(logTime)
        m_logEntries(m_count) = entry
        m_count = m_count + 1
    End Sub
    Public Function GetFormattedLog() As String
        ' Get formatted log with timestamps
        Dim i As Integer
        Dim result As String
        Dim timeStr As String
        result = "Event Log" & vbCrLf
        result = result & String(50, "-") & vbCrLf
        For i = 0 To m_count - 1
            timeStr = Format(m_logEntries(i).Timestamp, "yyyy-mm-dd hh:nn:ss")
            result = result & timeStr & " | " & m_logEntries(i).Message & vbCrLf
        Next i
        GetFormattedLog = result
    End Function
    Public Function GetEventsAtSecond(targetSecond As Integer) As String
        ' Get all events that occurred at a specific second
        Dim i As Integer
        Dim result As String
        Dim count As Integer
        result = "Events at second " & targetSecond & ":" & vbCrLf
        count = 0
        For i = 0 To m_count - 1
            If m_logEntries(i).Second = targetSecond Then
                result = result & "  " & _
                        Format(m_logEntries(i).Timestamp, "hh:nn:ss") & " | " & _
                        m_logEntries(i).Message & vbCrLf
                count = count + 1
            End If
        Next i
        result = result & vbCrLf & "Total: " & count & " events"
        GetEventsAtSecond = result
    End Function
    Public Function GetLogCount() As Integer
        GetLogCount = m_count
    End Function
    Public Sub ClearLog()
        m_count = 0
        ReDim m_logEntries(0 To 999)
    End Sub
End Module

Example 3: Time-Based Task Scheduler

' Schedule tasks to run at specific seconds
Class TaskScheduler
    Private Type ScheduledTask
        TaskName As String
        TargetSecond As Integer
        Interval As Integer
        LastRun As Date
        Enabled As Boolean
    End Type
    Private m_tasks() As ScheduledTask
    Private m_count As Integer
    Public Sub Initialize()
        m_count = 0
        ReDim m_tasks(0 To 99)
    End Sub
    Public Sub AddTask(taskName As String, targetSecond As Integer, _
                      Optional interval As Integer = 60)
        ' Add task to run at specific second
        If m_count > UBound(m_tasks) Then
            ReDim Preserve m_tasks(0 To UBound(m_tasks) + 50)
        End If
        m_tasks(m_count).TaskName = taskName
        m_tasks(m_count).TargetSecond = targetSecond
        m_tasks(m_count).Interval = interval
        m_tasks(m_count).LastRun = 0
        m_tasks(m_count).Enabled = True
        m_count = m_count + 1
    End Sub
    Public Function CheckTasks() As String
        ' Check which tasks should run now
        Dim currentTime As Date
        Dim currentSecond As Integer
        Dim i As Integer
        Dim tasksToRun As String
        Dim elapsedSeconds As Long
        currentTime = Now
        currentSecond = Second(currentTime)
        tasksToRun = ""
        For i = 0 To m_count - 1
            If m_tasks(i).Enabled Then
                If currentSecond = m_tasks(i).TargetSecond Then
                    If m_tasks(i).LastRun = 0 Then
                        ' First run
                        tasksToRun = tasksToRun & m_tasks(i).TaskName & ";"
                        m_tasks(i).LastRun = currentTime
                    Else
                        ' Check interval
                        elapsedSeconds = DateDiff("s", m_tasks(i).LastRun, currentTime)
                        If elapsedSeconds >= m_tasks(i).Interval Then
                            tasksToRun = tasksToRun & m_tasks(i).TaskName & ";"
                            m_tasks(i).LastRun = currentTime
                        End If
                    End If
                End If
            End If
        Next i
        CheckTasks = tasksToRun
    End Function
    Public Sub EnableTask(taskName As String)
        Dim i As Integer
        For i = 0 To m_count - 1
            If m_tasks(i).TaskName = taskName Then
                m_tasks(i).Enabled = True
                Exit Sub
            End If
        Next i
    End Sub
    Public Sub DisableTask(taskName As String)
        Dim i As Integer
        For i = 0 To m_count - 1
            If m_tasks(i).TaskName = taskName Then
                m_tasks(i).Enabled = False
                Exit Sub
            End If
        Next i
    End Sub
End Class

Example 4: Animation Timer

' Time-based animation controller using seconds
Class AnimationTimer
    Private m_startTime As Date
    Private m_duration As Integer  ' Duration in seconds
    Private m_running As Boolean
    Public Sub StartAnimation(durationSeconds As Integer)
        m_startTime = Now
        m_duration = durationSeconds
        m_running = True
    End Sub
    Public Function GetProgress() As Double
        ' Get animation progress (0.0 to 1.0)
        Dim elapsed As Long
        If Not m_running Then
            GetProgress = 0
            Exit Function
        End If
        elapsed = DateDiff("s", m_startTime, Now)
        If elapsed >= m_duration Then
            GetProgress = 1
            m_running = False
        Else
            GetProgress = elapsed / m_duration
        End If
    End Function
    Public Function GetElapsedSeconds() As Integer
        ' Get elapsed seconds since animation start
        If m_running Then
            GetElapsedSeconds = DateDiff("s", m_startTime, Now)
        Else
            GetElapsedSeconds = 0
        End If
    End Function
    Public Function GetRemainingSeconds() As Integer
        ' Get remaining seconds in animation
        Dim elapsed As Integer
        If Not m_running Then
            GetRemainingSeconds = 0
            Exit Function
        End If
        elapsed = DateDiff("s", m_startTime, Now)
        If elapsed >= m_duration Then
            GetRemainingSeconds = 0
            m_running = False
        Else
            GetRemainingSeconds = m_duration - elapsed
        End If
    End Function
    Public Function IsComplete() As Boolean
        IsComplete = Not m_running
    End Function
    Public Sub Stop()
        m_running = False
    End Sub
    Public Function GetCurrentSecond() As Integer
        GetCurrentSecond = Second(Now)
    End Function
End Class

Error Handling

The Second function generates errors in specific situations: Error 13: Type mismatch - Occurs when the argument cannot be interpreted as a date/time value Error 94: Invalid use of Null - Can occur if Null is passed and not handled properly Example error handling:

On Error Resume Next
Dim sec As Integer
sec = Second(userInput)
If Err.Number <> 0 Then
    MsgBox "Invalid time value"
    sec = 0
End If
On Error GoTo 0

Performance Considerations

Best Practices

  1. Validate Input: Check that input is valid date/time before calling
  2. Handle Null: Check for Null if data source is uncertain
  3. Use with Other Time Functions: Combine with Hour, Minute for complete parsing
  4. Format Consistently: Use consistent time formatting in your application
  5. Consider Time Zones: Be aware of time zone issues in time calculations
  6. Document Precision: Clarify if milliseconds matter in your application
  7. Use for Validation: Validate time components are in expected ranges
  8. Cache Now Values: If using Now multiple times, cache to avoid timing issues
  9. Test Edge Cases: Test with midnight, end of minute, etc.
  10. Use TimeSerial: Combine with TimeSerial to construct times
Function Purpose Returns Range
Second Get seconds Integer 0-59
Minute Get minutes Integer 0-59
Hour Get hours Integer 0-23
Day Get day Integer 1-31
Month Get month Integer 1-12
Year Get year Integer 100-9999
TimeSerial Create time Date Constructs time from H:M:S
DatePart Get date part Variant Flexible date/time extraction

Platform and Version Notes

Limitations

← Back to Datetime | View all functions