-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathcoverage.html
More file actions
2547 lines (2228 loc) · 103 KB
/
coverage.html
File metadata and controls
2547 lines (2228 loc) · 103 KB
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
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>gotime: Go Coverage Report</title>
<style>
body {
background: black;
color: rgb(80, 80, 80);
}
body, pre, #legend span {
font-family: Menlo, monospace;
font-weight: bold;
}
#topbar {
background: black;
position: fixed;
top: 0; left: 0; right: 0;
height: 42px;
border-bottom: 1px solid rgb(80, 80, 80);
}
#content {
margin-top: 50px;
}
#nav, #legend {
float: left;
margin-left: 10px;
}
#legend {
margin-top: 12px;
}
#nav {
margin-top: 10px;
}
#legend span {
margin: 0 5px;
}
.cov0 { color: rgb(192, 0, 0) }
.cov1 { color: rgb(128, 128, 128) }
.cov2 { color: rgb(116, 140, 131) }
.cov3 { color: rgb(104, 152, 134) }
.cov4 { color: rgb(92, 164, 137) }
.cov5 { color: rgb(80, 176, 140) }
.cov6 { color: rgb(68, 188, 143) }
.cov7 { color: rgb(56, 200, 146) }
.cov8 { color: rgb(44, 212, 149) }
.cov9 { color: rgb(32, 224, 152) }
.cov10 { color: rgb(20, 236, 155) }
</style>
</head>
<body>
<div id="topbar">
<div id="nav">
<select id="files">
<option value="file0">github.com/maniartech/gotime/age_calculation.go (100.0%)</option>
<option value="file1">github.com/maniartech/gotime/business_calendar.go (100.0%)</option>
<option value="file2">github.com/maniartech/gotime/calendar_math.go (100.0%)</option>
<option value="file3">github.com/maniartech/gotime/convert.go (100.0%)</option>
<option value="file4">github.com/maniartech/gotime/debug/debug_age.go (0.0%)</option>
<option value="file5">github.com/maniartech/gotime/examples/tinygo/main.go (0.0%)</option>
<option value="file6">github.com/maniartech/gotime/format.go (100.0%)</option>
<option value="file7">github.com/maniartech/gotime/internal/cache/cache.go (94.7%)</option>
<option value="file8">github.com/maniartech/gotime/internal/nites/convert.go (100.0%)</option>
<option value="file9">github.com/maniartech/gotime/internal/nites/format.go (100.0%)</option>
<option value="file10">github.com/maniartech/gotime/internal/nites/parse.go (100.0%)</option>
<option value="file11">github.com/maniartech/gotime/internal/utils/assert.go (92.9%)</option>
<option value="file12">github.com/maniartech/gotime/internal/utils/runtime.go (100.0%)</option>
<option value="file13">github.com/maniartech/gotime/misc.go (100.0%)</option>
<option value="file14">github.com/maniartech/gotime/parse.go (100.0%)</option>
<option value="file15">github.com/maniartech/gotime/quarters.go (100.0%)</option>
<option value="file16">github.com/maniartech/gotime/range.go (100.0%)</option>
<option value="file17">github.com/maniartech/gotime/relative_functions.go (100.0%)</option>
<option value="file18">github.com/maniartech/gotime/time_ago.go (100.0%)</option>
<option value="file19">github.com/maniartech/gotime/time_arithmetic.go (100.0%)</option>
<option value="file20">github.com/maniartech/gotime/time_calc.go (100.0%)</option>
<option value="file21">github.com/maniartech/gotime/weekday_count.go (100.0%)</option>
<option value="file22">github.com/maniartech/gotime/weekday_present.go (100.0%)</option>
</select>
</div>
<div id="legend">
<span>not tracked</span>
<span class="cov0">not covered</span>
<span class="cov8">covered</span>
</div>
</div>
<div id="content">
<pre class="file" id="file0" style="display: none">package gotime
import (
"fmt"
"time"
)
// Age calculates the precise age in years, months, and days between a birth date and a reference date.
// If no reference date is provided, it uses the current time.
//
// The calculation accounts for leap years and varying month lengths.
//
// Example:
//
// birthDate := time.Date(1990, 5, 15, 0, 0, 0, 0, time.UTC)
// asOf := time.Date(2025, 7, 7, 0, 0, 0, 0, time.UTC)
// years, months, days := gotime.Age(birthDate, asOf)
// // Returns: 35, 1, 23 (35 years, 1 month, 23 days)
func Age(birthDate time.Time, asOf ...time.Time) (years, months, days int) <span class="cov8" title="1">{
var ref time.Time
if len(asOf) > 0 </span><span class="cov8" title="1">{
ref = asOf[0]
}</span> else<span class="cov8" title="1"> {
ref = time.Now()
}</span>
// Ensure birth date is before reference date
<span class="cov8" title="1">if birthDate.After(ref) </span><span class="cov8" title="1">{
return 0, 0, 0
}</span>
// Use a more reliable approach: count years first, then months, then days
<span class="cov8" title="1">birth := time.Date(birthDate.Year(), birthDate.Month(), birthDate.Day(), 0, 0, 0, 0, birthDate.Location())
reference := time.Date(ref.Year(), ref.Month(), ref.Day(), 0, 0, 0, 0, ref.Location())
// Start with the birth year and increment until we can't add more years
currentDate := birth
for </span><span class="cov8" title="1">{
nextYear := currentDate.AddDate(1, 0, 0)
if nextYear.After(reference) </span><span class="cov8" title="1">{
break</span>
}
<span class="cov8" title="1">years++
currentDate = nextYear</span>
}
// Now add months
<span class="cov8" title="1">for </span><span class="cov8" title="1">{
nextMonth := currentDate.AddDate(0, 1, 0)
if nextMonth.After(reference) </span><span class="cov8" title="1">{
break</span>
}
<span class="cov8" title="1">months++
currentDate = nextMonth</span>
}
// Finally, count remaining days
<span class="cov8" title="1">for currentDate.Before(reference) </span><span class="cov8" title="1">{
days++
currentDate = currentDate.AddDate(0, 0, 1)
}</span>
<span class="cov8" title="1">return years, months, days</span>
}
// YearsBetween calculates the precise number of years between two dates as a float64.
// The result includes fractional years based on the exact time difference.
//
// Example:
//
// start := time.Date(2020, 1, 1, 0, 0, 0, 0, time.UTC)
// end := time.Date(2025, 7, 1, 0, 0, 0, 0, time.UTC)
// years := gotime.YearsBetween(start, end)
// // Returns: approximately 5.5 years
func YearsBetween(start, end time.Time) float64 <span class="cov8" title="1">{
// Ensure start is before end
if start.After(end) </span><span class="cov8" title="1">{
start, end = end, start
}</span>
<span class="cov8" title="1">duration := end.Sub(start)
// Average number of hours in a year (accounting for leap years)
// 365.2425 days per year * 24 hours per day
const hoursPerYear = 365.2425 * 24
return duration.Hours() / hoursPerYear</span>
}
// MonthsBetween calculates the precise number of months between two dates as a float64.
// The result includes fractional months based on the exact time difference.
//
// Example:
//
// start := time.Date(2025, 1, 1, 0, 0, 0, 0, time.UTC)
// end := time.Date(2025, 7, 15, 0, 0, 0, 0, time.UTC)
// months := gotime.MonthsBetween(start, end)
// // Returns: approximately 6.5 months
func MonthsBetween(start, end time.Time) float64 <span class="cov8" title="1">{
// Ensure start is before end
if start.After(end) </span><span class="cov8" title="1">{
start, end = end, start
}</span>
<span class="cov8" title="1">duration := end.Sub(start)
// Average number of hours in a month
// 365.2425 days per year / 12 months * 24 hours per day
const hoursPerMonth = (365.2425 / 12) * 24
return duration.Hours() / hoursPerMonth</span>
}
// DaysBetween calculates the number of days between two dates.
// This is a convenience function that returns the integer number of days.
//
// Example:
//
// start := time.Date(2025, 1, 1, 0, 0, 0, 0, time.UTC)
// end := time.Date(2025, 1, 8, 0, 0, 0, 0, time.UTC)
// days := gotime.DaysBetween(start, end)
// // Returns: 7
func DaysBetween(start, end time.Time) int <span class="cov8" title="1">{
// Ensure start is before end
if start.After(end) </span><span class="cov8" title="1">{
start, end = end, start
}</span>
<span class="cov8" title="1">duration := end.Sub(start)
return int(duration.Hours() / 24)</span>
}
// WeeksBetween calculates the precise number of weeks between two dates as a float64.
// The result includes fractional weeks based on the exact time difference.
//
// Example:
//
// start := time.Date(2025, 1, 1, 0, 0, 0, 0, time.UTC)
// end := time.Date(2025, 1, 11, 0, 0, 0, 0, time.UTC)
// weeks := gotime.WeeksBetween(start, end)
// // Returns: approximately 1.43 weeks
func WeeksBetween(start, end time.Time) float64 <span class="cov8" title="1">{
// Ensure start is before end
if start.After(end) </span><span class="cov8" title="1">{
start, end = end, start
}</span>
<span class="cov8" title="1">duration := end.Sub(start)
const hoursPerWeek = 7 * 24
return duration.Hours() / hoursPerWeek</span>
}
// DurationInWords returns a human-readable representation of a duration.
// It formats the duration in the most appropriate unit(s).
//
// Example:
//
// d := 2*time.Hour + 30*time.Minute
// result := gotime.DurationInWords(d)
// // Returns: "2 hours 30 minutes"
func DurationInWords(d time.Duration) string <span class="cov8" title="1">{
if d == 0 </span><span class="cov8" title="1">{
return "0 seconds"
}</span>
// Handle negative durations
<span class="cov8" title="1">negative := d < 0
if negative </span><span class="cov8" title="1">{
d = -d
}</span>
<span class="cov8" title="1">var parts []string
// Extract time components
days := int(d.Hours()) / 24
hours := int(d.Hours()) % 24
minutes := int(d.Minutes()) % 60
seconds := int(d.Seconds()) % 60
// Build the string with appropriate units
if days > 0 </span><span class="cov8" title="1">{
if days == 1 </span><span class="cov8" title="1">{
parts = append(parts, "1 day")
}</span> else<span class="cov8" title="1"> {
parts = append(parts, fmt.Sprintf("%d days", days))
}</span>
}
<span class="cov8" title="1">if hours > 0 </span><span class="cov8" title="1">{
if hours == 1 </span><span class="cov8" title="1">{
parts = append(parts, "1 hour")
}</span> else<span class="cov8" title="1"> {
parts = append(parts, fmt.Sprintf("%d hours", hours))
}</span>
}
<span class="cov8" title="1">if minutes > 0 </span><span class="cov8" title="1">{
if minutes == 1 </span><span class="cov8" title="1">{
parts = append(parts, "1 minute")
}</span> else<span class="cov8" title="1"> {
parts = append(parts, fmt.Sprintf("%d minutes", minutes))
}</span>
}
<span class="cov8" title="1">if seconds > 0 && len(parts) < 2 </span><span class="cov8" title="1">{ // Only show seconds if we don't have 2+ larger units
if seconds == 1 </span><span class="cov8" title="1">{
parts = append(parts, "1 second")
}</span> else<span class="cov8" title="1"> {
parts = append(parts, fmt.Sprintf("%d seconds", seconds))
}</span>
}
// Handle very small durations
<span class="cov8" title="1">if len(parts) == 0 </span><span class="cov8" title="1">{
return "less than 1 second"
}</span>
// Join parts appropriately
<span class="cov8" title="1">var result string
if len(parts) == 1 </span><span class="cov8" title="1">{
result = parts[0]
}</span> else<span class="cov8" title="1"> if len(parts) == 2 </span><span class="cov8" title="1">{
result = parts[0] + " " + parts[1]
}</span> else<span class="cov8" title="1"> {
// For 3+ parts, use only the first 2 most significant units
result = parts[0] + " " + parts[1]
}</span>
<span class="cov8" title="1">if negative </span><span class="cov8" title="1">{
result = "-" + result
}</span>
<span class="cov8" title="1">return result</span>
}
// IsValidAge checks if the given birth date results in a valid age (not negative, not unreasonably old).
// This is useful for validating user input for birth dates.
//
// Example:
//
// birthDate := time.Date(1990, 5, 15, 0, 0, 0, 0, time.UTC)
// valid := gotime.IsValidAge(birthDate)
// // Returns: true
func IsValidAge(birthDate time.Time, asOf ...time.Time) bool <span class="cov8" title="1">{
var ref time.Time
if len(asOf) > 0 </span><span class="cov8" title="1">{
ref = asOf[0]
}</span> else<span class="cov8" title="1"> {
ref = time.Now()
}</span>
// Birth date cannot be in the future
<span class="cov8" title="1">if birthDate.After(ref) </span><span class="cov8" title="1">{
return false
}</span>
// Calculate age in years
<span class="cov8" title="1">years := YearsBetween(birthDate, ref)
// Reasonable age limits (0 to 150 years) - use <= for inclusive range
return years >= 0 && years <= 150</span>
}
</pre>
<pre class="file" id="file1" style="display: none">package gotime
import "time"
// IsBusinessDay reports whether t is a business day (not a weekend or holiday).
//
// The weekends parameter specifies which weekdays are considered weekends
// (e.g., []time.Weekday{time.Saturday, time.Sunday}).
// The holidays parameter is a slice of time.Time representing holidays
// (only the date portion is considered, time is ignored).
//
// Example:
// weekends := []time.Weekday{time.Saturday, time.Sunday}
// holidays := []time.Time{time.Date(2025, 7, 4, 0, 0, 0, 0, time.UTC)}
// isBusiness := gotime.IsBusinessDay(time.Now(), weekends, holidays...)
// // isBusiness: true if today is not a weekend or holiday
func IsBusinessDay(t time.Time, weekends []time.Weekday, holidays ...time.Time) bool <span class="cov8" title="1">{
for _, w := range weekends </span><span class="cov8" title="1">{
if t.Weekday() == w </span><span class="cov8" title="1">{
return false
}</span>
}
<span class="cov8" title="1">for _, h := range holidays </span><span class="cov8" title="1">{
if sameDay(t, h) </span><span class="cov8" title="1">{
return false
}</span>
}
<span class="cov8" title="1">return true</span>
}
// NextBusinessDay returns the next business day after t, skipping weekends and holidays.
//
// Example:
// weekends := []time.Weekday{time.Saturday, time.Sunday}
// holidays := []time.Time{time.Date(2025, 7, 4, 0, 0, 0, 0, time.UTC)}
// nextBiz := gotime.NextBusinessDay(time.Now(), weekends, holidays...)
// // nextBiz: the next date that is not a weekend or holiday
func NextBusinessDay(t time.Time, weekends []time.Weekday, holidays ...time.Time) time.Time <span class="cov8" title="1">{
next := t.AddDate(0, 0, 1)
for !IsBusinessDay(next, weekends, holidays...) </span><span class="cov8" title="1">{
next = next.AddDate(0, 0, 1)
}</span>
<span class="cov8" title="1">return next</span>
}
// PrevBusinessDay returns the previous business day before t, skipping weekends and holidays.
//
// Example:
// weekends := []time.Weekday{time.Saturday, time.Sunday}
// holidays := []time.Time{time.Date(2025, 7, 4, 0, 0, 0, 0, time.UTC)}
// prevBiz := gotime.PrevBusinessDay(time.Now(), weekends, holidays...)
// // prevBiz: the previous date that is not a weekend or holiday
func PrevBusinessDay(t time.Time, weekends []time.Weekday, holidays ...time.Time) time.Time <span class="cov8" title="1">{
prev := t.AddDate(0, 0, -1)
for !IsBusinessDay(prev, weekends, holidays...) </span><span class="cov8" title="1">{
prev = prev.AddDate(0, 0, -1)
}</span>
<span class="cov8" title="1">return prev</span>
}
// sameDay checks if two times are on the same year, month, and day.
func sameDay(a, b time.Time) bool <span class="cov8" title="1">{
ay, am, ad := a.Date()
by, bm, bd := b.Date()
return ay == by && am == bm && ad == bd
}</span>
</pre>
<pre class="file" id="file2" style="display: none">package gotime
import "time"
// DayOfYear returns the day number (1-366) within the year for the given date.
// This uses Go's built-in YearDay() method for optimal performance.
//
// Example:
// gotime.DayOfYear(time.Date(2025, 1, 1, 0, 0, 0, 0, time.UTC)) // Returns 1
// gotime.DayOfYear(time.Date(2025, 12, 31, 0, 0, 0, 0, time.UTC)) // Returns 365
// gotime.DayOfYear(time.Date(2024, 12, 31, 0, 0, 0, 0, time.UTC)) // Returns 366 (leap year)
func DayOfYear(t time.Time) int <span class="cov8" title="1">{
return t.YearDay()
}</span>
// WeekOfMonth returns the week number (1-5) within the month for the given date.
// The first week starts on the 1st of the month, regardless of the day of the week.
// This follows the common business calendar convention.
//
// Example:
// gotime.WeekOfMonth(time.Date(2025, 7, 1, 0, 0, 0, 0, time.UTC)) // Returns 1
// gotime.WeekOfMonth(time.Date(2025, 7, 7, 0, 0, 0, 0, time.UTC)) // Returns 2
// gotime.WeekOfMonth(time.Date(2025, 7, 31, 0, 0, 0, 0, time.UTC)) // Returns 5
func WeekOfMonth(t time.Time) int <span class="cov8" title="1">{
firstOfMonth := time.Date(t.Year(), t.Month(), 1, 0, 0, 0, 0, t.Location())
firstWeekday := int(firstOfMonth.Weekday())
return (t.Day()+firstWeekday-1)/7 + 1
}</span>
// IsFirstDayOfMonth returns true if the date is the first day of its month.
// This is a high-performance check that simply compares the day component.
//
// Example:
// gotime.IsFirstDayOfMonth(time.Date(2025, 7, 1, 0, 0, 0, 0, time.UTC)) // Returns true
// gotime.IsFirstDayOfMonth(time.Date(2025, 7, 2, 0, 0, 0, 0, time.UTC)) // Returns false
func IsFirstDayOfMonth(t time.Time) bool <span class="cov8" title="1">{
return t.Day() == 1
}</span>
// IsLastDayOfMonth returns true if the date is the last day of its month.
// This efficiently checks by adding one day and seeing if the month changes.
// This approach correctly handles leap years and varying month lengths.
//
// Example:
// gotime.IsLastDayOfMonth(time.Date(2025, 2, 28, 0, 0, 0, 0, time.UTC)) // Returns true (non-leap year)
// gotime.IsLastDayOfMonth(time.Date(2024, 2, 29, 0, 0, 0, 0, time.UTC)) // Returns true (leap year)
// gotime.IsLastDayOfMonth(time.Date(2025, 7, 31, 0, 0, 0, 0, time.UTC)) // Returns true
// gotime.IsLastDayOfMonth(time.Date(2025, 7, 30, 0, 0, 0, 0, time.UTC)) // Returns false
func IsLastDayOfMonth(t time.Time) bool <span class="cov8" title="1">{
nextDay := t.AddDate(0, 0, 1)
return nextDay.Month() != t.Month()
}</span>
</pre>
<pre class="file" id="file3" style="display: none">package gotime
import "github.com/maniartech/gotime/internal/nites"
// Convert parses a date-time string according to the source format and
// reformats it using the target format. Both formats use NITES
// (Natural and Intuitive Time Expression Syntax) format specifiers.
//
// Example:
// converted, err := gotime.Convert("2022-12-31", "yyyy-mm-dd", "dt mmmm, yyyy")
// if err != nil {
// // handle error
// }
// // converted: "31st December, 2022"
func Convert(value, fromLayout, toLayout string) (string, error) <span class="cov8" title="1">{
return nites.Convert(value, fromLayout, toLayout)
}</span>
</pre>
<pre class="file" id="file4" style="display: none">package main
import (
"fmt"
"time"
)
// DaysInMonth returns the number of days in a given month of a given year
func DaysInMonth(year, month int) int <span class="cov0" title="0">{
// Go to the first day of the next month, then subtract one day
nextMonth := time.Date(year, time.Month(month+1), 1, 0, 0, 0, 0, time.UTC)
firstOfMonth := time.Date(year, time.Month(month), 1, 0, 0, 0, 0, time.UTC)
return int(nextMonth.Sub(firstOfMonth).Hours() / 24)
}</span>
func Age(birthDate time.Time, asOf time.Time) (years, months, days int) <span class="cov0" title="0">{
// Use a more reliable approach: count years first, then months, then days
birth := time.Date(birthDate.Year(), birthDate.Month(), birthDate.Day(), 0, 0, 0, 0, birthDate.Location())
reference := time.Date(asOf.Year(), asOf.Month(), asOf.Day(), 0, 0, 0, 0, asOf.Location())
fmt.Printf("Birth: %s\n", birth.Format("2006-01-02"))
fmt.Printf("AsOf: %s\n", reference.Format("2006-01-02"))
// Start with the birth year and increment until we can't add more years
currentDate := birth
for </span><span class="cov0" title="0">{
nextYear := currentDate.AddDate(1, 0, 0)
if nextYear.After(reference) </span><span class="cov0" title="0">{
break</span>
}
<span class="cov0" title="0">years++
currentDate = nextYear
fmt.Printf("Added year %d, current date: %s\n", years, currentDate.Format("2006-01-02"))</span>
}
// Now add months
<span class="cov0" title="0">for </span><span class="cov0" title="0">{
nextMonth := currentDate.AddDate(0, 1, 0)
if nextMonth.After(reference) </span><span class="cov0" title="0">{
break</span>
}
<span class="cov0" title="0">months++
currentDate = nextMonth
fmt.Printf("Added month %d, current date: %s\n", months, currentDate.Format("2006-01-02"))</span>
}
// Finally, count remaining days
<span class="cov0" title="0">for currentDate.Before(reference) </span><span class="cov0" title="0">{
days++
currentDate = currentDate.AddDate(0, 0, 1)
if days <= 5 </span><span class="cov0" title="0">{ // Limit output for debugging
fmt.Printf("Added day %d, current date: %s\n", days, currentDate.Format("2006-01-02"))
}</span>
}
<span class="cov0" title="0">return years, months, days</span>
}
func main() <span class="cov0" title="0">{
// Test case 1: years, months, and days
fmt.Println("=== Test 1: years, months, and days ===")
birthDate1 := time.Date(1990, 5, 15, 0, 0, 0, 0, time.UTC)
asOf1 := time.Date(2025, 7, 7, 0, 0, 0, 0, time.UTC)
years1, months1, days1 := Age(birthDate1, asOf1)
fmt.Printf("Expected: 35 years, 1 months, 23 days\n")
fmt.Printf("Got: %d years, %d months, %d days\n\n", years1, months1, days1)
// Test case 2: leap year birthday
fmt.Println("=== Test 2: leap year birthday ===")
birthDate2 := time.Date(2000, 2, 29, 0, 0, 0, 0, time.UTC)
asOf2 := time.Date(2025, 3, 1, 0, 0, 0, 0, time.UTC)
years2, months2, days2 := Age(birthDate2, asOf2)
fmt.Printf("Expected: 25 years, 0 months, 1 days\n")
fmt.Printf("Got: %d years, %d months, %d days\n\n", years2, months2, days2)
}</span>
</pre>
<pre class="file" id="file5" style="display: none">package main
import (
"fmt"
"time"
"github.com/maniartech/gotime"
)
func main() <span class="cov0" title="0">{
now := time.Date(2025, 7, 7, 12, 0, 0, 0, time.UTC)
fmt.Println("Now:", now)
// Add 5 days
future := gotime.Days(5, now)
fmt.Println("5 days from now:", future)
// Start of day
startOfDay := gotime.SoD(now)
fmt.Println("Start of day:", startOfDay)
// Is business day
weekends := []time.Weekday{time.Saturday, time.Sunday}
holiday := time.Date(2025, 7, 4, 0, 0, 0, 0, time.UTC)
isBiz := gotime.IsBusinessDay(now, weekends, holiday)
fmt.Println("Is business day:", isBiz)
}</span>
</pre>
<pre class="file" id="file6" style="display: none">package gotime
import (
"time"
"github.com/maniartech/gotime/internal/nites"
)
// Format converts a time.Time value to a formatted string using the specified layout.
// If layout is empty, RFC3339 format is used by default.
//
// The layout uses NITES (Natural and Intuitive Time Expression Syntax) format
// specifiers like "yyyy-mm-dd" instead of Go's reference time format.
//
// Example:
//
// formatted := gotime.Format(time.Now(), "yyyy-mm-dd")
// // formatted: "2025-07-08"
//
// formatted = gotime.Format(time.Now(), "mmmm dd, yyyy")
// // formatted: "July 08, 2025"
func Format(dt time.Time, layout string) string <span class="cov8" title="1">{
if layout == "" </span><span class="cov8" title="1">{
// Layout is RFC3339 by default
layout = time.RFC3339
}</span>
<span class="cov8" title="1">return nites.Format(dt, layout)</span>
}
// FormatUnix converts Unix time (seconds and nanoseconds) to a formatted string
// using the specified layout. If layout is empty, RFC3339 format is used by default.
//
// Example:
//
// formatted := gotime.FormatUnix(1609459200, 0, "yyyy-mm-dd")
// // formatted: "2021-01-01"
func FormatUnix(sec int64, nsec int64, layout string) string <span class="cov8" title="1">{
if layout == "" </span><span class="cov8" title="1">{
// Layout is RFC3339 by default
layout = time.RFC3339
}</span>
<span class="cov8" title="1">return nites.Format(time.Unix(sec, nsec), layout)</span>
}
// FormatTimestamp converts a Unix timestamp (seconds) to a formatted string
// using the specified layout. If layout is empty, RFC3339 format is used by default.
//
// Example:
//
// formatted := gotime.FormatTimestamp(1609459200, "yyyy-mm-dd")
// // formatted: "2021-01-01"
func FormatTimestamp(timestamp int64, layout string) string <span class="cov8" title="1">{
if layout == "" </span><span class="cov8" title="1">{
// Layout is RFC3339 by default
layout = time.RFC3339
}</span>
<span class="cov8" title="1">return nites.Format(time.Unix(timestamp, 0), layout)</span>
}
</pre>
<pre class="file" id="file7" style="display: none">package cache
var cache map[string]interface{}
func init() <span class="cov8" title="1">{
cache = map[string]interface{}{}
}</span>
// Disable disables the cache. This is useful for testing or
// when you want to make sure that the cache is not used. Generally,
// many applications do not need to disable the cache due to the limited
// number of datetime formats that are used. However, if you are using
// unknown number of datetime formats, then you may want to disable
// the cache. The cache is enabled by default. To reenable the cache,
// use the Enable function.
func Disable() <span class="cov8" title="1">{
cache = nil
}</span>
// Enable enables the cache. By default, the cache is enabled.
// This function is useful when you want to enable the cache after it has been
// disabled. See the Disable function for more information.
func Enable() <span class="cov8" title="1">{
cache = map[string]interface{}{}
}</span>
// IsEnabled returns true if the cache is enabled. The cache is
// enabled by default. See the Disable function for more information.
func IsEnabled() bool <span class="cov8" title="1">{
return cache != nil
}</span>
// Set sets the cache value for the given key. If the cache is disabled,
// this function does nothing.
func Set(key string, value interface{}) <span class="cov8" title="1">{
if cache == nil </span><span class="cov8" title="1">{
return
}</span>
<span class="cov8" title="1">cache[key] = value</span>
}
// Get returns the cache value for the given key. If the cache is disabled,
// this function returns nil.
func Get(key string) interface{} <span class="cov8" title="1">{
if cache == nil </span><span class="cov8" title="1">{
return nil
}</span>
<span class="cov8" title="1">return cache[key]</span>
}
func GetStrs(key string) []string <span class="cov8" title="1">{
if cache == nil </span><span class="cov8" title="1">{
return nil
}</span>
<span class="cov8" title="1">value, exists := cache[key]
if !exists </span><span class="cov0" title="0">{
return nil
}</span>
<span class="cov8" title="1">switch v := value.(type) </span>{
case []string:<span class="cov8" title="1">
return v</span>
case string:<span class="cov8" title="1">
return []string{v}</span>
default:<span class="cov8" title="1">
return nil</span>
}
}
</pre>
<pre class="file" id="file8" style="display: none">package nites
import (
"errors"
"strings"
"time"
"github.com/maniartech/gotime/internal/cache"
"github.com/maniartech/gotime/internal/utils"
)
// Convert function converts a datetime from one string format to another.
// It takes the datetime string in the single format and converts it to the expected output.
// It returns an error when the format is not supported.
func Convert(dt string, from string, to string) (string, error) <span class="cov8" title="1">{
if from == to </span><span class="cov8" title="1">{
return dt, nil
}</span>
// Convert the format to go format. While parsing
// the from layout, it may return an error if the format
// contains ordinals (mt, dt).
<span class="cov8" title="1">fromConverted, err := convertLayout(from, true)
if err != nil </span><span class="cov8" title="1">{
return "", err
}</span>
<span class="cov8" title="1">var fromLayout string
switch v := fromConverted.(type) </span>{
case []string:<span class="cov8" title="1">
fromLayout = v[0]</span>
default:<span class="cov8" title="1">
fromLayout, _ = v.(string)</span>
}
<span class="cov8" title="1">toLayout, _ := convertLayout(to, false) // ConvertLayout never returns an error when forParsing is false
t, err := time.Parse(fromLayout, dt)
if err != nil </span><span class="cov8" title="1">{
return "", err
}</span>
<span class="cov8" title="1">switch v := toLayout.(type) </span>{
case []string:<span class="cov8" title="1">
return formatStrs(t, v), nil</span>
default:<span class="cov8" title="1">
vstr, _ := v.(string)
return t.Format(vstr), nil</span>
}
}
// convertLayout converts this library datetime format to a go format.
// It loops through each character of the supplied format string
// and checks if it is a valid format character. If it is, it
// converts it to the go format.
//
// The function convert following format:
// yy -> 06 Two digit year with leading zero
// yyyy -> 2006 Four digit year
// m -> 1 Month without leading zero
// mm -> 01 Month in two digits with leading zero
// mt -> 1st Month in ordinal format with leading zero (not supported during parsing)
// mmm -> Jan Month in short name
// mmmm -> January Month in full name
// d -> 2 Day without leading zero
// dd -> 02 Day in two digits with leading zero
// dt -> 2nd Day in ordinal format with leading zero (not supported during parsing)
// ddd -> 002 Zero padded day of year
// www -> Mon Three letter weekday name
// wwww -> Monday Full weekday name
// h -> 3 Hour in 12 hour format without leading zero
// hh -> 03 Hour in 12 hour format with leading zero
// hhhh -> 15 Hour in 24 hour format with leading zero
// a -> pm am/pm (lowercase)
// aa -> PM AM/PM (uppercase)
// ii -> 04 Minute with leading zero
// i -> 4 Minute without leading zero
// ss -> 05 Second with leading zero
// s -> 5 Second without leading zero
// 0 -> 0 Microsecond with leading zero
// 9 -> 9 Microsecond without leading zero
// z -> Z The Z literal represents UTC
// zz -> MST Timezone abbreviation
// o -> ±07 Timezone offset with leading zero (only hours)
// oo -> ±0700 Timezone offset with leading zero without colon
// ooo -> ±07:00 Timezone offset with leading zero with colon
func convertLayout(f string, forParsing bool) (interface{}, error) <span class="cov8" title="1">{
// Built-in format, return as is
if version, ok := utils.BuiltInLayouts[f]; ok </span><span class="cov8" title="1">{
if utils.RuntimeVersion >= version </span><span class="cov8" title="1">{
return []string{f}, nil
}</span>
}
// If the format is cached, return the cached value
<span class="cov8" title="1">if v := cache.Get(f); v != nil </span><span class="cov8" title="1">{
return v, nil
}</span>
// Convert format to lower case for case insensitive matching
<span class="cov8" title="1">var converted interface{}
// Initialize a map of format conversions
conversions := map[string][][]string{
"y": {{"yyyy", "2006"}, {"yy", "06"}},
"m": {{"mmmm", "January"}, {"mmm", "Jan"}, {"mm", "01"}, {"mt", ""}, {"m", "1"}},
"d": {{"ddd", "002"}, {"dd", "02"}, {"db", "_2"}, {"dt", ""}, {"d", "2"}}, // dt for ordinals
"w": {{"wwww", "Monday"}, {"www", "Mon"}},
"h": {{"hhhh", "15"}, {"hh", "03"}, {"h", "3"}},
"a": {{"aa", "PM"}, {"a", "pm"}},
"i": {{"ii", "04"}, {"i", "4"}},
"s": {{"ss", "05"}, {"s", "5"}},
// Timezone
"z": {
{"zz", "MST"},
{"z", "Z"},
},
"o": {{"ooo", "-07:00"}, {"oo", "-0700"}, {"o", "-07"}},
}
// Initialize a new string builder
to := strings.Builder{}
// Loop through the input format
i := 0
for i < len(f) </span><span class="cov8" title="1">{
c := f[i]
// If c is uppercase, convert it to lowercase
if c >= 'A' && c <= 'Z' </span><span class="cov8" title="1">{
c += 32
}</span>
// Check if the current character is an escape character
<span class="cov8" title="1">if f[i] == '\\' </span><span class="cov8" title="1">{
// Check if we're not at the end of the format string
if i+1 < len(f) </span><span class="cov8" title="1">{
// Append the next character as a literal, ignoring its format meaning
to.WriteString(string(f[i+1]))
i += 2
}</span> else<span class="cov8" title="1"> {
// We're at the end of the format string; append the escape character
to.WriteString(string(f[i]))
i++
}</span>
<span class="cov8" title="1">continue</span>
}
// Check if the current character is a valid format character
<span class="cov8" title="1">conv, ok := conversions[string(c)]
if !ok </span><span class="cov8" title="1">{
// Not a valid format character, add as is
to.WriteString(string(f[i]))
i++
continue</span>
}
// Valid format character, check for the longest possible match
<span class="cov8" title="1">for _, keyVal := range conv </span><span class="cov8" title="1">{
key, val := keyVal[0], keyVal[1]
iEnd := i + len(key)
// Check if the len of key + i is less than the len of the format.
if iEnd <= len(f) </span><span class="cov8" title="1">{
if f[i:iEnd] == key </span><span class="cov8" title="1">{
if val == "" </span><span class="cov8" title="1">{
if forParsing </span><span class="cov8" title="1">{
return nil, errors.New(errOrdinalsNotSupported)
}</span>
<span class="cov8" title="1">if converted == nil </span><span class="cov8" title="1">{
converted = []string{}
}</span>
<span class="cov8" title="1">converted = append(converted.([]string), to.String()) // Append the converted format
converted = append(converted.([]string), key) // Append the value to the converted format
to.Reset()</span>
}
<span class="cov8" title="1">to.WriteString(val)
i += len(key)
goto MatchFound</span>
}
}
}
// If we get here, we didn't find a match, add the character as is
<span class="cov8" title="1">if i < len(f) </span><span class="cov8" title="1">{
to.WriteString(string(f[i]))
i++
}</span>
MatchFound:
}
// Cache the converted format
<span class="cov8" title="1">finalConvert := to.String()
if converted == nil </span><span class="cov8" title="1">{
cache.Set(f, finalConvert)
return finalConvert, nil
}</span>
<span class="cov8" title="1">converted = append(converted.([]string), finalConvert)
cache.Set(f, converted)
return converted, nil</span>
}
</pre>
<pre class="file" id="file9" style="display: none">package nites
import (
"fmt"
"strconv"
"time"
)
// This file contains the IDF (Intuitive Date Format) conversion functions
// for the gotime package.
// Format formats a time.Time value according to the given layout string.
// The layout uses intuitive date format (IDF) syntax instead of Go's reference time.
// Supports ordinal formatting for days (dt) and months (mt).
//
// Example formats:
//
// "yyyy-mm-dd" -> "2025-07-07"
// "dt of mmm" -> "7th of Jul"
// "mt month" -> "7th month"
//
// See convertLayout documentation for complete format specification.
func Format(dt time.Time, layout string) string <span class="cov8" title="1">{
convertedLayouts, _ := convertLayout(layout, false)
if str, ok := convertedLayouts.(string); ok </span><span class="cov8" title="1">{
return dt.Format(str)
}</span>
<span class="cov8" title="1">return formatStrs(dt, convertedLayouts.([]string))</span>
}
// formatStrs formats a time using multiple layout strings and concatenates the results.
// This function is used when the layout contains ordinal formats (dt, mt) that require
// special processing beyond standard Go time formatting.
func formatStrs(dt time.Time, convertedLayouts []string) string <span class="cov8" title="1">{