-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathparser.go
More file actions
995 lines (883 loc) · 30.9 KB
/
Copy pathparser.go
File metadata and controls
995 lines (883 loc) · 30.9 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
// Package dateline provides comprehensive date and time parsing capabilities for Go.
// It can detect and parse dates/times from strings in over 150+ different formats,
// including ISO 8601, RFC formats, Unix timestamps, relative dates, and multilingual dates.
//
// The parser automatically detects the format and can optionally remove the parsed
// date from the original string. It supports finding multiple dates in a single string
// and handles various timezone formats.
//
// Basic usage:
//
// result, err := dateline.Parse("Meeting on March 15, 2024 at 2:30 PM", false)
// if err != nil {
// log.Fatal(err)
// }
// fmt.Printf("Parsed: %s\n", result.Time.Format("2006-01-02 15:04:05"))
//
// Find all dates:
//
// results, err := dateline.FindAllDates("From 2024-01-01 to 2024-12-31")
// for _, r := range results {
// fmt.Printf("Found: %s\n", r.Time)
// }
//
// Remove date from string:
//
// result, err := dateline.Parse("Error on 2024-03-15 - investigate", true)
// fmt.Println(result.StringWithout) // "Error on - investigate"
package dateline
import (
"fmt"
"regexp"
"strconv"
"strings"
"time"
)
// ParseResult contains the results of parsing a date/time from a string.
// It includes the parsed time value, the format used, position information,
// and optionally the string with the date removed.
type ParseResult struct {
// Time is the parsed time.Time value
Time time.Time
// Format indicates which format pattern was used for parsing
// (e.g., "iso_week", "unix", "relative", "2006-01-02", etc.)
Format string
// OriginalText is the complete input string that was parsed
OriginalText string
// StartIndex is the character position where the date starts in the original string
// (0 if the entire string was parsed)
StartIndex int
// EndIndex is the character position where the date ends in the original string
// (0 if the entire string was parsed)
EndIndex int
// ParsedString is the actual substring that was successfully parsed as a date
ParsedString string
// StringWithout is the original string with the parsed date removed
// (only populated if removal was requested)
StringWithout string
}
// commonFormats contains the list of time format patterns to try when parsing.
// These use Go's time format syntax where the reference time is:
// Mon Jan 2 15:04:05 MST 2006, which is Unix time 1136239445.
// The formats are tried in order, so more specific formats should come first.
var commonFormats = []string{
// ISO 8601 and variants (including Go reference format)
"2006-01-02T15:04:05Z07:00",
"2006-01-02T15:04:05Z",
"2006-01-02T15:04:05",
"2006-01-02 15:04:05",
"2006-01-02",
"20060102T150405Z",
"20060102T150405",
"20060102",
// Go specific formats
"Jan 2, 2006 at 3:04pm (MST)",
"Jan _2 15:04:05",
"Jan _2 15:04:05.000",
"Monday, 02-Jan-06 15:04:05 MST",
"Mon Jan 2 15:04:05 -0700 2006",
"02 Jan 06 15:04 MST",
"02 Jan 06 15:04 -0700",
// Bracketed and parentheses formats
"[02/Jan/2006:15:04:05 -0700]",
"[15/Mar/2024:14:30:45 +0000]",
"[2006-01-02T15:04:05Z]",
"[2006-01-02 15:04:05]",
"(2006-01-02T15:04:05Z)",
"(2006-01-02 15:04:05)",
"(Mon Jan _2 15:04:05 2006)",
// RFC formats
"Mon, 02 Jan 2006 15:04:05 MST",
"Mon, 02 Jan 2006 15:04:05 -0700",
"02 Jan 2006 15:04:05 MST",
"Monday, 02-Jan-06 15:04:05 MST",
"Mon Jan _2 15:04:05 MST 2006",
"Mon Jan _2 15:04:05 2006",
"Mon Jan 02 15:04:05 -0700 2006",
time.RFC3339,
time.RFC3339Nano,
time.RFC822,
time.RFC822Z,
time.RFC850,
time.RFC1123,
time.RFC1123Z,
// American formats
"01/02/2006",
"1/2/2006",
"01/02/06",
"1/2/06",
"01-02-2006",
"01.02.2006",
"01 02 2006",
"January 2, 2006",
"Jan 2, 2006",
"January 2nd, 2006",
"Jan. 2, 2006",
"January 2 2006",
"2 January 2006",
"2nd January 2006",
"2nd January, 2006",
// European formats
"02/01/2006",
"2/1/2006",
"02.01.2006",
"02-01-2006",
"02 01 2006",
"2 January 2006",
"2. January 2006",
// Time formats with dates
"2006-01-02 15:04:05.999999999",
"2006-01-02 15:04:05.999999",
"2006-01-02 15:04:05.999",
"01/02/2006 15:04:05",
"01/02/2006 3:04:05 PM",
"01/02/2006 3:04 PM",
"2006/01/02 15:04:05",
"02.01.2006 15:04:05",
"02-01-2006 15:04:05",
// MySQL/PostgreSQL
"2006-01-02 15:04:05",
"2006-01-02 15:04:05.999999",
// Log formats
"Jan _2 15:04:05",
"Jan _2 2006 15:04:05",
"02/Jan/2006:15:04:05 -0700",
// Compact formats
"Jan 2",
"2 Jan",
"01-02",
"Jan-02",
"02-Jan",
"2006-01",
"01/2006",
"Jan 2006",
"January 2006",
// With timezone
"2006-01-02T15:04:05-07:00",
"2006-01-02 15:04:05 MST",
"2006-01-02 15:04:05 -0700",
"2006-01-02 15:04:05 -07:00",
// Additional formats
"2006/01/02",
"02.01.2006",
"02-01-2006",
"2006.01.02",
"2006_01_02",
"20060102_150405",
"2006-01-02_15-04-05",
// Database formats (Oracle, etc.)
"02-Jan-06",
"02-JAN-06",
"02-Jan-2006",
"02-JAN-2006",
"02-Jan-06 15.04.05",
"02-JAN-2006 15:04:05.999999",
// More technical formats
"2006.01.02_15:04:05",
"2006/01/02-15:04:05",
"02.01.2006-15:04:05",
// 12-hour formats
"3:04 PM",
"3:04:05 PM",
"3:04:05.999 PM",
"03:04 PM",
"3:04PM",
"3:04 pm",
"3:04 P.M.",
"3:04p",
}
// monthNames maps month names in various languages to Go's time.Month values.
// Used for parsing dates with non-English month names.
// All keys should be lowercase for case-insensitive matching.
var monthNames = map[string]time.Month{
"january": time.January, "jan": time.January,
"february": time.February, "feb": time.February,
"march": time.March, "mar": time.March,
"april": time.April, "apr": time.April,
"may": time.May,
"june": time.June, "jun": time.June,
"july": time.July, "jul": time.July,
"august": time.August, "aug": time.August,
"september": time.September, "sep": time.September, "sept": time.September,
"october": time.October, "oct": time.October,
"november": time.November, "nov": time.November,
"december": time.December, "dec": time.December,
// French
"janvier": time.January, "février": time.February, "mars": time.March,
"avril": time.April, "mai": time.May, "juin": time.June,
"juillet": time.July, "août": time.August, "septembre": time.September,
"octobre": time.October, "novembre": time.November, "décembre": time.December,
// Spanish
"enero": time.January, "febrero": time.February, "marzo": time.March,
"abril": time.April, "mayo": time.May, "junio": time.June,
"julio": time.July, "agosto": time.August, "septiembre": time.September,
"octubre": time.October, "noviembre": time.November, "diciembre": time.December,
// German
"januar": time.January, "februar": time.February, "märz": time.March,
"juni": time.June, "juli": time.July,
"oktober": time.October, "dezember": time.December,
// Italian
"gennaio": time.January, "febbraio": time.February,
"aprile": time.April, "maggio": time.May, "giugno": time.June,
"luglio": time.July, "settembre": time.September,
"ottobre": time.October, "dicembre": time.December,
// Portuguese
"janeiro": time.January, "fevereiro": time.February, "março": time.March,
"maio": time.May, "junho": time.June,
"julho": time.July, "setembro": time.September,
"outubro": time.October, "novembro": time.November,
}
// dateRegexes contains compiled regular expressions for finding potential dates
// in text. These patterns are tried in order to locate date-like strings which
// are then passed to tryParseDate for actual parsing.
// The patterns are ordered with more specific formats first to avoid false matches.
var dateRegexes = []*regexp.Regexp{
// Bracketed formats (priority - check first)
regexp.MustCompile(`\[\d{1,2}/(?:Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)/\d{4}:\d{2}:\d{2}:\d{2}\s+[+-]\d{4}\]`),
regexp.MustCompile(`\[[^\]]*\d{4}[^\]]*\]`),
regexp.MustCompile(`\([^)]*\d{4}[^)]*\)`),
// ISO formats
regexp.MustCompile(`\b\d{4}-\d{1,2}-\d{1,2}(?:[T\s]\d{1,2}:\d{1,2}(?::\d{1,2})?(?:\.\d+)?(?:Z|[+-]\d{2}:?\d{2})?)?\b`),
regexp.MustCompile(`\b\d{8}(?:T\d{6}(?:Z)?)?\b`),
// ISO Week formats
regexp.MustCompile(`\b\d{4}-W\d{1,2}(?:-\d)?\b`),
regexp.MustCompile(`\b\d{4}W\d{2}\d?\b`),
regexp.MustCompile(`\bW\d{1,2}[/\-]\d{4}\b`),
regexp.MustCompile(`\bCW\d{1,2}\s+\d{4}\b`),
// Quarter formats
regexp.MustCompile(`\bQ[1-4]\s+\d{4}\b`),
regexp.MustCompile(`\b\d{4}\s+Q[1-4]\b`),
regexp.MustCompile(`\b\d{4}Q[1-4]\b`),
regexp.MustCompile(`\b[1-4]Q\d{4}\b`),
regexp.MustCompile(`\bQ[1-4][/\-]\d{4}\b`),
// Database formats (Oracle, etc.)
regexp.MustCompile(`\b\d{1,2}-(?:JAN|FEB|MAR|APR|MAY|JUN|JUL|AUG|SEP|OCT|NOV|DEC)-\d{2,4}\b`),
regexp.MustCompile(`\b\d{1,2}-(?:Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)-\d{2,4}\b`),
// American/European date formats
regexp.MustCompile(`\b\d{1,2}[/\-\.]\d{1,2}[/\-\.]\d{2,4}\b`),
regexp.MustCompile(`\b\d{2,4}[/\-\.]\d{1,2}[/\-\.]\d{1,2}\b`),
// Written dates (multilingual)
regexp.MustCompile(`\b(?:January|February|March|April|May|June|July|August|September|October|November|December|Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Sept|Oct|Nov|Dec|janvier|février|mars|avril|mai|juin|juillet|août|septembre|octobre|novembre|décembre|enero|febrero|marzo|abril|mayo|junio|julio|agosto|septiembre|octubre|noviembre|diciembre|januar|februar|märz|juni|juli|oktober|dezember)\.?\s+\d{1,2}(?:st|nd|rd|th)?(?:,?\s+\d{2,4})?\b`),
regexp.MustCompile(`\b\d{1,2}(?:st|nd|rd|th)?\s+(?:of\s+)?(?:January|February|March|April|May|June|July|August|September|October|November|December|Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Sept|Oct|Nov|Dec|mars|marzo|märz|mai|juin|julio|agosto)\.?(?:,?\s+\d{2,4})?\b`),
regexp.MustCompile(`\b\d{1,2}\s+de\s+(?:enero|febrero|marzo|abril|mayo|junio|julio|agosto|septiembre|octubre|noviembre|diciembre)\s+de\s+\d{4}\b`),
// Time patterns
regexp.MustCompile(`\b\d{1,2}:\d{2}(?::\d{2})?(?:\.\d+)?(?:\s*(?:AM|PM|am|pm|A\.M\.|P\.M\.|a|p))?\b`),
// Unix timestamps (10-19 digits)
regexp.MustCompile(`\b\d{10,19}\b`),
regexp.MustCompile(`@\d{10,19}\b`),
// Asian formats
regexp.MustCompile(`\d{2,4}年\d{1,2}月\d{1,2}日`),
regexp.MustCompile(`\d{2,4}년\s*\d{1,2}월\s*\d{1,2}일`),
// Log format
regexp.MustCompile(`\b(?:Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\s+\d{1,2}\s+\d{1,2}:\d{2}:\d{2}\b`),
// Technical formats with underscores, special separators
regexp.MustCompile(`\b\d{8}_\d{6}\b`),
regexp.MustCompile(`\b\d{4}[_\-\.]\d{2}[_\-\.]\d{2}[_\-]\d{2}[_\-]\d{2}[_\-]\d{2}\b`),
}
// Parse attempts to find and parse a date/time from the input string.
// It tries multiple parsing strategies in order:
// 1. Relative dates (e.g., "today", "yesterday", "2 days ago")
// 2. Standard formats (150+ predefined formats)
// 3. Pattern matching using regular expressions
// 4. Unix timestamps (seconds, milliseconds, microseconds, nanoseconds)
//
// The removeDate parameter determines whether the parsed date should be removed
// from the original string. If true, the StringWithout field will contain the
// input with the date removed.
//
// Returns a ParseResult with the parsed time and metadata, or an error if no
// date could be found.
//
// Example:
//
// result, err := Parse("Meeting on 2024-03-15 at 3pm", false)
// if err != nil {
// return err
// }
// fmt.Println(result.Time) // 2024-03-15 00:00:00 +0000 UTC
// fmt.Println(result.ParsedString) // "2024-03-15"
// fmt.Println(result.StartIndex) // 11
func Parse(input string, removeDate bool) (*ParseResult, error) {
result := &ParseResult{
OriginalText: input,
}
// Try relative dates first
if parsedTime, ok := parseRelativeDate(input); ok {
result.Time = parsedTime
result.Format = "relative"
result.ParsedString = input
if removeDate {
result.StringWithout = ""
} else {
result.StringWithout = input
}
return result, nil
}
// Try standard formats
for _, format := range commonFormats {
if t, err := time.Parse(format, input); err == nil {
result.Time = t
result.Format = format
result.ParsedString = input
if removeDate {
result.StringWithout = ""
} else {
result.StringWithout = input
}
return result, nil
}
}
// Try to find dates using regex patterns
for _, re := range dateRegexes {
if matches := re.FindStringIndex(input); matches != nil {
dateStr := input[matches[0]:matches[1]]
// Try to parse the matched string
parsedTime, format, err := tryParseDate(dateStr)
if err == nil {
result.Time = parsedTime
result.Format = format
result.ParsedString = dateStr
result.StartIndex = matches[0]
result.EndIndex = matches[1]
if removeDate {
result.StringWithout = strings.TrimSpace(input[:matches[0]] + input[matches[1]:])
} else {
result.StringWithout = input
}
return result, nil
}
// Try Unix timestamp
if ts, ok := parseUnixTimestamp(dateStr); ok {
result.Time = ts
result.Format = "unix"
result.ParsedString = dateStr
result.StartIndex = matches[0]
result.EndIndex = matches[1]
if removeDate {
result.StringWithout = strings.TrimSpace(input[:matches[0]] + input[matches[1]:])
} else {
result.StringWithout = input
}
return result, nil
}
}
}
// Try to find and parse any number that could be a Unix timestamp
if ts, start, end, ok := findUnixTimestamp(input); ok {
result.Time = ts
result.Format = "unix"
result.ParsedString = input[start:end]
result.StartIndex = start
result.EndIndex = end
if removeDate {
result.StringWithout = strings.TrimSpace(input[:start] + input[end:])
} else {
result.StringWithout = input
}
return result, nil
}
return nil, fmt.Errorf("no date/time found in input string")
}
// tryParseDate attempts to parse a date string using multiple strategies.
// It tries ISO week formats, quarter formats, bracketed formats, common formats,
// multilingual dates, and various normalizations.
// Returns the parsed time, the format identifier used, and an error if parsing failed.
func tryParseDate(dateStr string) (time.Time, string, error) {
// Clean the string
dateStr = strings.TrimSpace(dateStr)
// Try ISO week dates first
if t, format, err := parseISOWeek(dateStr); err == nil {
return t, format, nil
}
// Try quarter formats
if t, format, err := parseQuarter(dateStr); err == nil {
return t, format, nil
}
// Try bracketed formats by removing brackets
cleaned := dateStr
if (strings.HasPrefix(dateStr, "[") && strings.HasSuffix(dateStr, "]")) ||
(strings.HasPrefix(dateStr, "(") && strings.HasSuffix(dateStr, ")")) {
cleaned = dateStr[1 : len(dateStr)-1]
if t, format, err := tryParseDate(cleaned); err == nil {
return t, "bracketed_" + format, nil
}
}
// Try all common formats
for _, format := range commonFormats {
if t, err := time.Parse(format, dateStr); err == nil {
return t, format, nil
}
}
// Try multilingual month parsing
if t, format, err := parseMultilingualDate(dateStr); err == nil {
return t, format, nil
}
// Try with normalized separators
normalized := dateStr
normalized = strings.ReplaceAll(normalized, ".", "/")
normalized = strings.ReplaceAll(normalized, "-", "/")
for _, format := range []string{"01/02/2006", "02/01/2006", "2006/01/02"} {
if t, err := time.Parse(format, normalized); err == nil {
return t, format, nil
}
}
// Try removing ordinal suffixes
ordinalCleaned := regexp.MustCompile(`(\d+)(?:st|nd|rd|th)`).ReplaceAllString(dateStr, "$1")
if ordinalCleaned != dateStr {
return tryParseDate(ordinalCleaned)
}
return time.Time{}, "", fmt.Errorf("unable to parse date: %s", dateStr)
}
// parseRelativeDate handles natural language date expressions like "today", "yesterday",
// "2 days ago", "next Friday", etc. It supports various relative time expressions
// and day names with "last" or "next" prefixes.
// Returns the calculated time and true if successful, or zero time and false if not a relative date.
func parseRelativeDate(input string) (time.Time, bool) {
lower := strings.ToLower(strings.TrimSpace(input))
now := time.Now()
switch lower {
case "today":
return now, true
case "yesterday":
return now.AddDate(0, 0, -1), true
case "tomorrow":
return now.AddDate(0, 0, 1), true
case "now":
return now, true
}
// Parse relative patterns like "2 days ago", "in 3 hours", etc.
relativePatterns := []struct {
re *regexp.Regexp
unit string
}{
{regexp.MustCompile(`^(\d+)\s+(second|seconds?)\s+ago$`), "second"},
{regexp.MustCompile(`^(\d+)\s+(minute|minutes?)\s+ago$`), "minute"},
{regexp.MustCompile(`^(\d+)\s+(hour|hours?)\s+ago$`), "hour"},
{regexp.MustCompile(`^(\d+)\s+(day|days?)\s+ago$`), "day"},
{regexp.MustCompile(`^(\d+)\s+(week|weeks?)\s+ago$`), "week"},
{regexp.MustCompile(`^(\d+)\s+(month|months?)\s+ago$`), "month"},
{regexp.MustCompile(`^(\d+)\s+(year|years?)\s+ago$`), "year"},
{regexp.MustCompile(`^in\s+(\d+)\s+(second|seconds?)$`), "second_future"},
{regexp.MustCompile(`^in\s+(\d+)\s+(minute|minutes?)$`), "minute_future"},
{regexp.MustCompile(`^in\s+(\d+)\s+(hour|hours?)$`), "hour_future"},
{regexp.MustCompile(`^in\s+(\d+)\s+(day|days?)$`), "day_future"},
{regexp.MustCompile(`^in\s+(\d+)\s+(week|weeks?)$`), "week_future"},
{regexp.MustCompile(`^in\s+(\d+)\s+(month|months?)$`), "month_future"},
{regexp.MustCompile(`^in\s+(\d+)\s+(year|years?)$`), "year_future"},
}
for _, pattern := range relativePatterns {
if matches := pattern.re.FindStringSubmatch(lower); matches != nil {
n, _ := strconv.Atoi(matches[1])
future := strings.HasSuffix(pattern.unit, "_future")
unit := strings.TrimSuffix(pattern.unit, "_future")
if !future {
n = -n
}
switch unit {
case "second":
return now.Add(time.Duration(n) * time.Second), true
case "minute":
return now.Add(time.Duration(n) * time.Minute), true
case "hour":
return now.Add(time.Duration(n) * time.Hour), true
case "day":
return now.AddDate(0, 0, n), true
case "week":
return now.AddDate(0, 0, n*7), true
case "month":
return now.AddDate(0, n, 0), true
case "year":
return now.AddDate(n, 0, 0), true
}
}
}
// Check for day names
weekdays := map[string]time.Weekday{
"monday": time.Monday, "mon": time.Monday,
"tuesday": time.Tuesday, "tue": time.Tuesday, "tues": time.Tuesday,
"wednesday": time.Wednesday, "wed": time.Wednesday,
"thursday": time.Thursday, "thu": time.Thursday, "thurs": time.Thursday,
"friday": time.Friday, "fri": time.Friday,
"saturday": time.Saturday, "sat": time.Saturday,
"sunday": time.Sunday, "sun": time.Sunday,
}
if strings.HasPrefix(lower, "last ") {
dayName := strings.TrimPrefix(lower, "last ")
if weekday, ok := weekdays[dayName]; ok {
daysBack := int(now.Weekday() - weekday)
if daysBack <= 0 {
daysBack += 7
}
return now.AddDate(0, 0, -daysBack), true
}
}
if strings.HasPrefix(lower, "next ") {
dayName := strings.TrimPrefix(lower, "next ")
if weekday, ok := weekdays[dayName]; ok {
daysForward := int(weekday - now.Weekday())
if daysForward <= 0 {
daysForward += 7
}
return now.AddDate(0, 0, daysForward), true
}
}
return time.Time{}, false
}
// parseUnixTimestamp attempts to parse a string as a Unix timestamp.
// It automatically detects whether the timestamp is in seconds, milliseconds,
// microseconds, or nanoseconds based on the number of digits.
// Also handles timestamps with @ prefix and floating-point timestamps.
// Returns the parsed time and true if successful, or zero time and false if not a timestamp.
func parseUnixTimestamp(s string) (time.Time, bool) {
// Remove @ prefix if present
s = strings.TrimPrefix(s, "@")
// Try to parse as number
if num, err := strconv.ParseInt(s, 10, 64); err == nil {
// Determine if it's seconds, milliseconds, microseconds, or nanoseconds
switch len(s) {
case 10: // seconds
return time.Unix(num, 0), true
case 13: // milliseconds
return time.Unix(num/1000, (num%1000)*1e6), true
case 16: // microseconds
return time.Unix(num/1e6, (num%1e6)*1000), true
case 19: // nanoseconds
return time.Unix(num/1e9, num%1e9), true
default:
// Try to guess based on reasonable date range
// Seconds: 1000000000 (2001) to 2000000000 (2033)
if num >= 1000000000 && num < 2000000000 {
return time.Unix(num, 0), true
}
// Milliseconds: 1000000000000 (2001) to 2000000000000 (2033)
if num >= 1000000000000 && num < 2000000000000 {
return time.Unix(num/1000, (num%1000)*1e6), true
}
}
}
// Try parsing as float (with decimal)
if num, err := strconv.ParseFloat(s, 64); err == nil {
sec := int64(num)
nsec := int64((num - float64(sec)) * 1e9)
return time.Unix(sec, nsec), true
}
return time.Time{}, false
}
// findUnixTimestamp searches for Unix timestamps within a larger string.
// It looks for 10-19 digit numbers (with or without @ prefix) that could
// represent timestamps in seconds, milliseconds, microseconds, or nanoseconds.
// Returns the parsed time, start position, end position, and true if found.
func findUnixTimestamp(input string) (time.Time, int, int, bool) {
// Look for 10-19 digit numbers that could be Unix timestamps
re := regexp.MustCompile(`\b\d{10,19}\b`)
if matches := re.FindStringIndex(input); matches != nil {
numStr := input[matches[0]:matches[1]]
if ts, ok := parseUnixTimestamp(numStr); ok {
return ts, matches[0], matches[1], true
}
}
// Look for @-prefixed timestamps
re = regexp.MustCompile(`@\d{10,19}\b`)
if matches := re.FindStringIndex(input); matches != nil {
numStr := input[matches[0]:matches[1]]
if ts, ok := parseUnixTimestamp(numStr); ok {
return ts, matches[0], matches[1], true
}
}
return time.Time{}, 0, 0, false
}
// ParseWithOptions provides more control over parsing behavior through functional options.
// This allows for customization of timezone handling and other parsing parameters.
//
// Available options:
// - WithDateRemoval(bool): Controls whether to remove the date from the string
// - WithLocation(*time.Location): Sets the timezone for parsing ambiguous times
//
// Example:
//
// nyc, _ := time.LoadLocation("America/New_York")
// result, err := ParseWithOptions(
// "Meeting at 3pm tomorrow",
// WithLocation(nyc),
// WithDateRemoval(true),
// )
func ParseWithOptions(input string, opts ...ParseOption) (*ParseResult, error) {
config := &parseConfig{
removeDate: false,
location: time.Local,
}
for _, opt := range opts {
opt(config)
}
result, err := Parse(input, config.removeDate)
if err != nil {
return nil, err
}
// Adjust for location if needed
if config.location != nil && result.Time.Location() != config.location {
result.Time = result.Time.In(config.location)
}
return result, nil
}
// parseConfig holds configuration options for parsing
type parseConfig struct {
removeDate bool
location *time.Location
}
// ParseOption is a functional option type for configuring parsing behavior
type ParseOption func(*parseConfig)
// WithDateRemoval returns a ParseOption that controls whether the parsed date
// should be removed from the original string.
//
// Example:
//
// result, _ := ParseWithOptions(text, WithDateRemoval(true))
// fmt.Println(result.StringWithout) // Original text with date removed
func WithDateRemoval(remove bool) ParseOption {
return func(c *parseConfig) {
c.removeDate = remove
}
}
// WithLocation returns a ParseOption that sets the timezone location for
// parsing ambiguous times that don't include timezone information.
//
// Example:
//
// tokyo, _ := time.LoadLocation("Asia/Tokyo")
// result, _ := ParseWithOptions("3:00 PM", WithLocation(tokyo))
func WithLocation(loc *time.Location) ParseOption {
return func(c *parseConfig) {
c.location = loc
}
}
// FindAllDates searches for and parses all dates found in the input string.
// It processes the string sequentially, finding dates from left to right.
// Each found date includes its position in the original string.
//
// Returns a slice of ParseResult structs, one for each date found, or an
// error if no dates could be found.
//
// Example:
//
// results, err := FindAllDates("From 2024-01-01 to 2024-12-31")
// if err != nil {
// return err
// }
// for _, r := range results {
// fmt.Printf("Date: %s at position [%d:%d]\n",
// r.Time.Format("2006-01-02"), r.StartIndex, r.EndIndex)
// }
func FindAllDates(input string) ([]*ParseResult, error) {
var results []*ParseResult
remaining := input
offset := 0
for remaining != "" {
result, err := Parse(remaining, false)
if err != nil {
break
}
// Adjust indices based on offset
result.StartIndex += offset
result.EndIndex += offset
results = append(results, result)
// Move past this date
if result.EndIndex > result.StartIndex {
offset += result.EndIndex
remaining = input[offset:]
} else {
break
}
}
if len(results) == 0 {
return nil, fmt.Errorf("no dates found in input")
}
return results, nil
}
// parseISOWeek parses ISO 8601 week date formats.
// Supports formats like:
// - 2024-W11 (year and week number)
// - 2024-W11-5 (year, week, and day of week)
// - 2024W115 (compact format)
//
// The week numbering follows ISO 8601 standards where week 1 is the first
// week with a Thursday in the new year.
// Returns the calculated date, format identifier, and any error.
func parseISOWeek(dateStr string) (time.Time, string, error) {
// 2024-W11 format
weekRe := regexp.MustCompile(`^(\d{4})-W(\d{1,2})$`)
if matches := weekRe.FindStringSubmatch(dateStr); matches != nil {
year, _ := strconv.Atoi(matches[1])
week, _ := strconv.Atoi(matches[2])
// Calculate date from ISO week
jan1 := time.Date(year, time.January, 1, 0, 0, 0, 0, time.UTC)
// Find first Monday of the year
daysToMonday := (8 - int(jan1.Weekday())) % 7
if jan1.Weekday() == time.Sunday {
daysToMonday = 1
}
firstMonday := jan1.AddDate(0, 0, daysToMonday)
weekDate := firstMonday.AddDate(0, 0, 7*(week-1))
return weekDate, "iso_week", nil
}
// 2024-W11-5 format (with day)
weekDayRe := regexp.MustCompile(`^(\d{4})-W(\d{1,2})-(\d)$`)
if matches := weekDayRe.FindStringSubmatch(dateStr); matches != nil {
year, _ := strconv.Atoi(matches[1])
week, _ := strconv.Atoi(matches[2])
day, _ := strconv.Atoi(matches[3])
// Calculate date from ISO week and day
jan1 := time.Date(year, time.January, 1, 0, 0, 0, 0, time.UTC)
daysToMonday := (8 - int(jan1.Weekday())) % 7
if jan1.Weekday() == time.Sunday {
daysToMonday = 1
}
firstMonday := jan1.AddDate(0, 0, daysToMonday)
weekDate := firstMonday.AddDate(0, 0, 7*(week-1)+(day-1))
return weekDate, "iso_week_day", nil
}
// 2024W115 format
compactWeekRe := regexp.MustCompile(`^(\d{4})W(\d{2})(\d)?$`)
if matches := compactWeekRe.FindStringSubmatch(dateStr); matches != nil {
year, _ := strconv.Atoi(matches[1])
week, _ := strconv.Atoi(matches[2])
day := 1
if matches[3] != "" {
day, _ = strconv.Atoi(matches[3])
}
jan1 := time.Date(year, time.January, 1, 0, 0, 0, 0, time.UTC)
daysToMonday := (8 - int(jan1.Weekday())) % 7
if jan1.Weekday() == time.Sunday {
daysToMonday = 1
}
firstMonday := jan1.AddDate(0, 0, daysToMonday)
weekDate := firstMonday.AddDate(0, 0, 7*(week-1)+(day-1))
return weekDate, "iso_week_compact", nil
}
return time.Time{}, "", fmt.Errorf("not an ISO week format")
}
// parseQuarter parses business quarter date formats.
// Supports various formats including:
// - Q1 2024
// - 2024 Q1
// - 2024Q1
// - 1Q2024
// - Q1/2024 or Q1-2024
//
// Quarters are mapped to the first day of the quarter:
// Q1 = January 1, Q2 = April 1, Q3 = July 1, Q4 = October 1
// Returns the first day of the quarter, format identifier, and any error.
func parseQuarter(dateStr string) (time.Time, string, error) {
quarterFormats := []struct {
re *regexp.Regexp
format string
}{
{regexp.MustCompile(`^Q([1-4])\s+(\d{4})$`), "quarter_space"},
{regexp.MustCompile(`^(\d{4})\s+Q([1-4])$`), "quarter_year_first"},
{regexp.MustCompile(`^(\d{4})Q([1-4])$`), "quarter_compact"},
{regexp.MustCompile(`^([1-4])Q(\d{4})$`), "quarter_number_first"},
{regexp.MustCompile(`^Q([1-4])[/\-](\d{4})$`), "quarter_separator"},
{regexp.MustCompile(`^Q([1-4])-(\d{4})$`), "quarter_dash"},
}
for _, qf := range quarterFormats {
matches := qf.re.FindStringSubmatch(dateStr)
if matches != nil {
var year, quarter int
var err error
if qf.format == "quarter_year_first" {
year, _ = strconv.Atoi(matches[1])
quarter, _ = strconv.Atoi(matches[2])
} else if qf.format == "quarter_number_first" {
quarter, _ = strconv.Atoi(matches[1])
year, _ = strconv.Atoi(matches[2])
} else {
quarter, _ = strconv.Atoi(matches[1])
year, _ = strconv.Atoi(matches[2])
}
if err != nil || quarter < 1 || quarter > 4 {
continue
}
// Convert quarter to first month of quarter
month := time.Month((quarter-1)*3 + 1)
quarterDate := time.Date(year, month, 1, 0, 0, 0, 0, time.UTC)
return quarterDate, qf.format, nil
}
}
return time.Time{}, "", fmt.Errorf("not a quarter format")
}
// parseMultilingualDate handles dates with month names in various languages.
// Currently supports month names in:
// - English (January, Jan)
// - Spanish (enero, marzo)
// - French (janvier, mars)
// - German (Januar, März)
// - Italian (gennaio, marzo)
// - Portuguese (janeiro, março)
//
// It attempts to match various date patterns with these month names,
// including formats like "15 mars 2024" or "15 de marzo de 2024".
// Returns the parsed date, format identifier with the month language, and any error.
func parseMultilingualDate(dateStr string) (time.Time, string, error) {
lower := strings.ToLower(dateStr)
// Try to find month names in different languages
for monthName, month := range monthNames {
if strings.Contains(lower, monthName) {
// Try various patterns with this month name
patterns := []string{
fmt.Sprintf(`(\d{1,2})\s+%s\s+(\d{2,4})`, monthName),
fmt.Sprintf(`%s\s+(\d{1,2}),?\s+(\d{2,4})`, monthName),
fmt.Sprintf(`(\d{1,2})\.?\s+%s\.?\s+(\d{2,4})`, monthName),
fmt.Sprintf(`(\d{1,2})\s+de\s+%s\s+de\s+(\d{2,4})`, monthName), // Spanish "de"
}
for _, pattern := range patterns {
re := regexp.MustCompile(pattern)
matches := re.FindStringSubmatch(lower)
if matches != nil {
var day, year int
var err error
if strings.Contains(pattern, "de") {
// Spanish format with "de"
day, err = strconv.Atoi(matches[1])
if err != nil {
continue
}
year, err = strconv.Atoi(matches[2])
if err != nil {
continue
}
} else if strings.Contains(pattern, `%s\s+\(\d`) {
// Month first format
day, err = strconv.Atoi(matches[1])
if err != nil {
continue
}
year, err = strconv.Atoi(matches[2])
if err != nil {
continue
}
} else {
// Day first format
day, err = strconv.Atoi(matches[1])
if err != nil {
continue
}
year, err = strconv.Atoi(matches[2])
if err != nil {
continue
}
}
// Handle 2-digit years
if year < 100 {
if year < 50 {
year += 2000
} else {
year += 1900
}
}
date := time.Date(year, month, day, 0, 0, 0, 0, time.UTC)
return date, "multilingual_" + monthName, nil
}
}
}
}
return time.Time{}, "", fmt.Errorf("not a multilingual date format")
}