1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
//! # Second Function
//!
//! Returns an Integer specifying a whole number between 0 and 59, inclusive, representing the second of the minute.
//!
//! ## Syntax
//!
//! ```vb
//! Second(time)
//! ```
//!
//! ## Parameters
//!
//! - `time` - Required. Any Variant, numeric expression, string expression, or any combination that can represent a time. If `time` contains Null, Null is returned.
//!
//! ## 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
//! ```vb
//! Dim currentSecond As Integer
//! currentSecond = Second(Now) ' Returns 0-59
//! ```
//!
//! ### Example 2: Parse Time String
//! ```vb
//! Dim timeStr As String
//! Dim sec As Integer
//!
//! timeStr = "3:45:30 PM"
//! sec = Second(timeStr) ' Returns 30
//! ```
//!
//! ### Example 3: Check Specific Second
//! ```vb
//! If Second(Now) = 0 Then
//! MsgBox "New minute started!"
//! End If
//! ```
//!
//! ### Example 4: Extract from Date/Time
//! ```vb
//! 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`
//! ```vb
//! 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`
//! ```vb
//! 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`
//! ```vb
//! 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`
//! ```vb
//! 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`
//! ```vb
//! 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`
//! ```vb
//! 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`
//! ```vb
//! 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`
//! ```vb
//! 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`
//! ```vb
//! 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`
//! ```vb
//! 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
//! ```vb
//! ' 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
//! ```vb
//! ' 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
//! ```vb
//! ' 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
//! ```vb
//! ' 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:
//!
//! ```vb
//! 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
//!
//! - `Second` is very fast - simple extraction operation
//! - No significant performance considerations
//! - Can be called thousands of times with minimal impact
//! - Consider caching if calling repeatedly on same value
//!
//! ## 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
//!
//! ## Comparison with Related Functions
//!
//! | 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
//!
//! - Available in all versions of VB6 and VBA
//! - Behavior consistent across all platforms
//! - In VB.NET, replaced by DateTime.Second property
//! - Returns Integer type (not Long)
//! - Always returns 0-59 range
//!
//! ## Limitations
//!
//! - No millisecond precision
//! - Cannot distinguish leap seconds
//! - Range limited to 0-59 (no support for values outside this range)
//! - Date portion of Date/Time value is ignored
//! - Cannot be used as `LValue` (cannot assign to Second)
//!
//! ## Related Functions
//!
//! - `Minute`: Returns the minute of the hour (0-59)
//! - `Hour`: Returns the hour of the day (0-23)
//! - `Now`: Returns the current system date and time
//! - `Time`: Returns the current system time
//! - `TimeSerial`: Returns a Date value for a specific time
//! - `DatePart`: Returns a specified part of a given date
//! - `Timer`: Returns seconds since midnight as Single
use crate;
use crate;
/// Implementation of the `Second` function.
///
/// VB6 behavior:
/// - a `Null` time returns `Null`
/// - the second is extracted from the date serial, so date-only values return 0
/// - the result is an `Integer` from 0 (start of the minute) to 59
/// - a value that cannot be interpreted as a date raises error 13 (type
/// mismatch)