-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstrtotime.go
More file actions
1977 lines (1754 loc) · 55.6 KB
/
strtotime.go
File metadata and controls
1977 lines (1754 loc) · 55.6 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
package strtotime
import (
"errors"
"fmt"
"strconv"
"strings"
"time"
)
// resolveOptions processes StrToTime options and returns the base time and location.
func resolveOptions(opts []Option) (time.Time, *time.Location) {
var now time.Time
loc := time.Local
tzExplicit := false
for _, opt := range opts {
switch v := opt.(type) {
case Rel:
now = time.Time(v)
case tzOption:
if v.loc != nil {
loc = v.loc
tzExplicit = true
}
}
}
if !now.IsZero() && !tzExplicit {
loc = now.Location()
}
if now.IsZero() {
now = time.Now().In(loc)
} else if now.Location() != loc {
now = now.In(loc)
}
return now, loc
}
// tryParseUnixTimestamp handles "@timestamp" and "@timestamp.fraction [TZ]" format.
func tryParseUnixTimestamp(str string, loc *time.Location) (time.Time, bool) {
if len(str) == 0 || str[0] != '@' {
return time.Time{}, false
}
unixTimeStr := str[1:]
tzParts := strings.SplitN(unixTimeStr, " ", 2)
timestamp := tzParts[0]
applyTZ := func(result time.Time) time.Time {
if len(tzParts) > 1 && tzParts[1] != "" {
if tzLoc, found := tryParseTimezone(tzParts[1]); found {
return result.In(tzLoc)
}
}
return result
}
if idx := strings.Index(timestamp, "."); idx != -1 {
unixTime, err := strconv.ParseInt(timestamp[:idx], 10, 64)
if err != nil {
return time.Time{}, false
}
fracStr := timestamp[idx+1:]
// PHP rejects fractional seconds with more than 6 digits
if len(fracStr) > 6 {
return time.Time{}, false
}
fracPart, err := strconv.ParseFloat("0."+fracStr, 64)
if err != nil {
fracPart = 0.0
}
nanoSec := int64(fracPart * 1e9)
return applyTZ(time.Unix(unixTime, nanoSec).In(loc)), true
}
unixTime, err := strconv.ParseInt(timestamp, 10, 64)
if err != nil {
return time.Time{}, false
}
return applyTZ(time.Unix(unixTime, 0).In(loc)), true
}
// tryKeyword handles keyword time expressions: now, today, tomorrow, yesterday, midnight, noon.
func tryKeyword(str string, now time.Time, loc *time.Location) (time.Time, bool) {
switch str {
case "now":
return now, true
case "today", "midnight":
y, m, d := now.Date()
return time.Date(y, m, d, 0, 0, 0, 0, loc), true
case "tomorrow":
t := now.AddDate(0, 0, 1)
y, m, d := t.Date()
return time.Date(y, m, d, 0, 0, 0, 0, loc), true
case "yesterday":
t := now.AddDate(0, 0, -1)
y, m, d := t.Date()
return time.Date(y, m, d, 0, 0, 0, 0, loc), true
case "noon":
y, m, d := now.Date()
return time.Date(y, m, d, 12, 0, 0, 0, loc), true
}
return time.Time{}, false
}
// tryWeekdayPrefixReparse strips a leading weekday name and reparses the rest.
// Handles: "Sun 2017-01-01", "Fri Aug 20 1993 23:59:59", etc.
func tryWeekdayPrefixReparse(str string, now time.Time, loc *time.Location, opts []Option) (time.Time, bool) {
rest, prefixDayNum, stripped := stripWeekdayPrefix(str)
if !stripped {
return time.Time{}, false
}
// Don't strip if rest is "next/last/this week" — the token parser handles these
restTrimmed := strings.TrimSpace(rest)
if strings.HasPrefix(restTrimmed, "next ") || strings.HasPrefix(restTrimmed, "last ") || strings.HasPrefix(restTrimmed, "this ") {
return time.Time{}, false
}
// Don't strip the weekday when the remaining text is just a time
// keyword — PHP treats "Monday noon" as weekday + time offset, not
// "Monday" anchoring an absolute date.
switch restTrimmed {
case "noon", "midnight", "tomorrow", "yesterday", "today", "now":
return time.Time{}, false
}
// Similarly reject when the rest is a bare time expression without any
// date component, so "Monday 10am" / "Tuesday 13:00" reach the token
// parser which records a weekday + time rather than anchoring today.
if restLooksLikeBareTime(restTrimmed) {
return time.Time{}, false
}
// Propagate the effective location so DateParse (zero base time, UTC)
// doesn't leak the caller's local timezone into the reparse.
reparseOpts := append([]Option(nil), opts...)
reparseOpts = append(reparseOpts, InTZ(loc))
t, err := StrToTime(rest, reparseOpts...)
if err != nil {
return time.Time{}, false
}
// PHP behavior: if the weekday prefix doesn't match the parsed date,
// advance to the next matching weekday
if prefixDayNum >= 0 && int(t.Weekday()) != prefixDayNum {
daysUntil := (prefixDayNum - int(t.Weekday()) + 7) % 7
if daysUntil == 0 {
daysUntil = 7
}
t = t.AddDate(0, 0, daysUntil)
}
return t, true
}
// restLooksLikeBareTime reports whether s is a time-of-day expression that
// lacks any date component (no dash/slash date markers, no 4-digit year).
func restLooksLikeBareTime(s string) bool {
if strings.Contains(s, "-") || strings.Contains(s, "/") {
return false
}
// HH:MM / HH:MM:SS variants.
if strings.Contains(s, ":") && !strings.ContainsAny(s, "abcdefghijklmnopqrstuvwxyz") {
return true
}
// Bare hour + am/pm ("10am", "9 pm", "8:30 am").
lower := strings.ToLower(s)
if strings.HasSuffix(lower, "am") || strings.HasSuffix(lower, "pm") {
prefix := strings.TrimSpace(strings.TrimSuffix(strings.TrimSuffix(lower, "am"), "pm"))
for _, r := range prefix {
if (r >= '0' && r <= '9') || r == ':' || r == ' ' || r == '.' {
continue
}
return false
}
return len(prefix) > 0
}
return false
}
// StrToTime will convert the provided string into a time similarly to how PHP strtotime() works.
func StrToTime(str string, opts ...Option) (time.Time, error) {
now, loc := resolveOptions(opts)
str = strings.ToLower(strings.TrimSpace(str))
if str == "" {
return time.Time{}, ErrEmptyTimeString
}
pd := newParsedDate()
if !dispatchStrToTime(str, now, loc, opts, pd) {
return time.Time{}, fmt.Errorf("unable to parse time string: %s", str)
}
if pd.ErrorCount > 0 {
return time.Time{}, fmt.Errorf("unable to parse time string: %s: %s", str, pd.firstError())
}
return pd.Materialize(now, loc)
}
// dispatchStrToTime runs the shared parse pipeline and returns true if any
// stage matched. It is also the body of DateParse (with a zero base time).
func dispatchStrToTime(str string, now time.Time, loc *time.Location, opts []Option, pd *ParsedDate) bool {
if parseUnixTimestampInto(str, loc, pd) {
return true
}
if parseKeywordInto(str, now, loc, pd) {
return true
}
for _, parser := range formatParsers {
sub := newParsedDate()
if parser(str, now, loc, opts, sub) {
copyComponents(pd, sub)
if sub.hasMaterialized {
pd.setMaterialized(sub.materialized)
}
if sub.Relative != nil {
pd.Relative = sub.Relative
}
if sub.relativeApplied {
pd.relativeApplied = true
}
return true
}
}
if parseDateWithRelativeTimeInto(str, now, loc, opts, pd) {
return true
}
if tryWeekdayPrefixReparseInto(str, now, loc, opts, pd) {
return true
}
if isCompoundExpression(str) {
// Try to parse purely-relative compounds (e.g. "-1 week +2 days")
// by accumulating into the Relative block without collapsing to an
// absolute time.
if parseCompoundRelativeInto(str, now, loc, opts, pd) {
return true
}
if t, err := parseCompoundExpression(str, now, opts); err == nil {
pd.SetDate(t.Year(), int(t.Month()), t.Day())
pd.SetTime(t.Hour(), t.Minute(), t.Second())
pd.setMaterialized(t)
return true
} else {
pd.AddError(0, err.Error())
return false
}
}
if parseOrdinalDateInto(str, now, loc, pd) {
return true
}
parser := &Parser{
tokens: Tokenize(str),
position: 0,
result: now,
loc: loc,
pd: pd,
}
result, err := parser.Parse()
if err != nil {
// The parser may have populated per-character errors already;
// only emit a fallback if nothing was recorded.
if pd.ErrorCount == 0 {
pd.AddError(0, err.Error())
}
return false
}
// Token parser mutates p.result in place, so the returned time already
// has any relative offsets baked in. Record relativeApplied so that
// Materialize doesn't double-apply the Relative block the parser also
// populated for DateParse reporting.
pd.setMaterialized(result)
pd.relativeApplied = true
return true
}
// Parser represents a token stream parser for time expressions
type Parser struct {
tokens []Token
position int
result time.Time
loc *time.Location
tzFound bool // Flag to indicate if a timezone was parsed from the input
monthFound bool // Flag to indicate if a month name was parsed (affects 4-digit number interpretation)
pd *ParsedDate // optional; when non-nil, tryParse* methods populate components
}
// Parse processes the token stream and returns a time.Time result
func (p *Parser) Parse() (time.Time, error) {
// Skip any leading whitespace
p.skipWhitespace()
// Try standard date formats first
if t, ok, err := p.tryParseStandardDate(); ok {
return t, err
}
// Try relative expressions
for p.position < len(p.tokens) {
// Skip whitespace between expressions
p.skipWhitespace()
if p.position >= len(p.tokens) {
break
}
// Try to parse each expression type
parsed := false
// Try to parse timezone
if !p.tzFound {
if ok := p.tryParseTimezone(); ok {
parsed = true
}
}
// Try "first/last day of this/next/last month/year"
if !parsed {
if t, ok, err := p.tryParseFirstLastDayOfExpression(); ok {
if err != nil {
return time.Time{}, err
}
p.result = t
parsed = true
}
}
// Try "next/last" expressions
if !parsed {
if t, ok, err := p.tryParseNextLastExpression(); ok {
if err != nil {
return time.Time{}, err
}
p.result = t
parsed = true
}
}
// Try bare weekday or "weekday next/last week [time]"
if !parsed {
if t, ok, err := p.tryParseBareWeekday(); ok {
if err != nil {
return time.Time{}, err
}
p.result = t
parsed = true
}
}
// Try +/- relative time
if !parsed {
if t, ok, err := p.tryParseRelativeTime(); ok {
if err != nil {
return time.Time{}, err
}
p.result = t
parsed = true
}
}
// Try implicit positive relative time (e.g., "4 days" without explicit +)
if !parsed {
if t, ok, err := p.tryParseImplicitRelativeTime(); ok {
if err != nil {
return time.Time{}, err
}
p.result = t
parsed = true
}
}
// Try "N weekday ago"
if !parsed {
if t, ok, err := p.tryParseWeekdayAgo(); ok {
if err != nil {
return time.Time{}, err
}
p.result = t
parsed = true
}
}
// Try ordinal word + unit (e.g., "eighth day")
if !parsed {
if t, ok, err := p.tryParseOrdinalRelativeTime(); ok {
if err != nil {
return time.Time{}, err
}
p.result = t
parsed = true
}
}
// Try standalone time expression "HH:MM[:SS]"
if !parsed {
if t, ok, err := p.tryParseTimeExpression(); ok {
if err != nil {
return time.Time{}, err
}
p.result = t
parsed = true
}
}
// Try bare hour with am/pm "10am", "10 pm"
if !parsed {
if t, ok, err := p.tryParseBareHourAMPM(); ok {
if err != nil {
return time.Time{}, err
}
p.result = t
parsed = true
}
}
// Try day keywords "tomorrow" / "yesterday" / "today" / "now"
if !parsed {
if t, ok, err := p.tryParseDayKeyword(); ok {
if err != nil {
return time.Time{}, err
}
p.result = t
parsed = true
}
}
// Try time keywords "midnight" / "noon"
if !parsed {
if t, ok, err := p.tryParseTimeKeyword(); ok {
if err != nil {
return time.Time{}, err
}
p.result = t
parsed = true
}
}
// Try month only format (e.g., "January" or "Feb")
if !parsed {
if t, ok, err := p.tryParseMonthOnlyFormat(); ok {
if err != nil {
return time.Time{}, err
}
p.result = t
p.monthFound = true
parsed = true
}
}
// Try month name format
if !parsed {
if t, ok, err := p.tryParseMonthNameFormat(); ok {
if err != nil {
return time.Time{}, err
}
p.result = t
p.monthFound = true
parsed = true
}
}
// Try bare 4-digit year (must be last number check)
if !parsed {
if t, ok, err := p.tryParseYearOnly(); ok {
if err != nil {
return time.Time{}, err
}
p.result = t
parsed = true
}
}
// Handle unrecognized token
if !parsed && p.position < len(p.tokens) {
currentToken := p.tokens[p.position]
p.position++
if currentToken.Typ != TypeWhitespace {
// PHP quirk: the filler words "at"/"on" inside an otherwise
// valid expression are reported as unknown-TZ errors, not
// per-character unexpected characters.
lower := strings.ToLower(currentToken.Val)
if (lower == "at" || lower == "on") && p.pd != nil {
p.pd.IsLocaltime = true
p.pd.ZoneType = 0
p.pd.AddError(currentToken.Pos, "The timezone could not be found in the database")
continue
}
if p.pd != nil {
// PHP-compatible: one "Unexpected character" per byte.
for i := range currentToken.Val {
p.pd.AddError(currentToken.Pos+i, "Unexpected character")
}
}
return time.Time{}, fmt.Errorf("unexpected token: %s", currentToken.Val)
}
}
// Skip whitespace after expressions
p.skipWhitespace()
}
return p.result, nil
}
// skipWhitespace advances the position past any whitespace tokens
func (p *Parser) skipWhitespace() {
for p.position < len(p.tokens) && p.tokens[p.position].Typ == TypeWhitespace {
p.position++
}
}
// tryParseTimezone attempts to parse a timezone from the token stream
// This handles abbreviations (PST, EST), slash-separated paths (America/New_York,
// America/Argentina/Buenos_Aires), hyphenated names (America/Port-au-Prince),
// and multi-word names (Eastern Time).
func (p *Parser) tryParseTimezone() bool {
if p.position >= len(p.tokens) {
return false
}
// Must start with a string token
if p.tokens[p.position].Typ != TypeString {
return false
}
startPos := p.position
// Try single token timezone first (EST, GMT, etc.)
tzString := p.tokens[p.position].Val
if loc, found := tryParseTimezone(tzString); found {
p.loc = loc
p.tzFound = true
p.position++
p.result = p.result.In(p.loc)
if p.pd != nil {
setTZFromName(p.pd, tzString, loc)
}
return true
}
// Try extending with / and - to build timezone paths like
// America/New_York, America/Argentina/Buenos_Aires, America/Port-au-Prince
var bestLoc *time.Location
var bestName string
bestPos := -1
pos := p.position + 1
for pos+1 < len(p.tokens) {
sep := p.tokens[pos]
if sep.Typ != TypeOperator || (sep.Val != "/" && sep.Val != "-") {
break
}
next := p.tokens[pos+1]
if next.Typ != TypeString {
break
}
tzString = tzString + sep.Val + next.Val
pos += 2
if loc, found := tryParseTimezone(tzString); found {
bestLoc = loc
bestName = tzString
bestPos = pos
}
}
if bestLoc != nil {
p.loc = bestLoc
p.tzFound = true
p.position = bestPos
p.result = p.result.In(p.loc)
if p.pd != nil {
setTZFromName(p.pd, bestName, bestLoc)
}
return true
}
// Try parsing multi-word timezone names (like "Eastern Time")
if p.position+2 < len(p.tokens) &&
p.tokens[p.position+1].Typ == TypeWhitespace &&
p.tokens[p.position+2].Typ == TypeString {
tzString = p.tokens[p.position].Val + " " + p.tokens[p.position+2].Val
if loc, found := tryParseTimezone(tzString); found {
p.loc = loc
p.tzFound = true
p.position += 3
p.result = p.result.In(p.loc)
if p.pd != nil {
setTZFromName(p.pd, tzString, loc)
}
return true
}
}
p.position = startPos
return false
}
// tryParseStandardDate attempts to parse standard date formats like ISO dates
func (p *Parser) tryParseStandardDate() (time.Time, bool, error) {
// Check if we have enough tokens for a date format (at least 5 tokens: num op num op num)
if p.position+4 >= len(p.tokens) {
return time.Time{}, false, nil
}
// First make sure we have potential date format tokens
if p.tokens[p.position].Typ != TypeNumber ||
p.tokens[p.position+2].Typ != TypeNumber ||
p.tokens[p.position+4].Typ != TypeNumber {
return time.Time{}, false, nil
}
// Get the first three numbers (potential year, month, day in some order)
firstNum, err1 := strconv.Atoi(p.tokens[p.position].Val)
if err1 != nil {
return time.Time{}, false, fmt.Errorf("invalid number in date: %w", err1)
}
secondNum, err2 := strconv.Atoi(p.tokens[p.position+2].Val)
if err2 != nil {
return time.Time{}, false, fmt.Errorf("invalid number in date: %w", err2)
}
thirdNum, err3 := strconv.Atoi(p.tokens[p.position+4].Val)
if err3 != nil {
return time.Time{}, false, fmt.Errorf("invalid number in date: %w", err3)
}
// Check the separators
if p.tokens[p.position+1].Typ != TypeOperator || p.tokens[p.position+3].Typ != TypeOperator {
return time.Time{}, false, nil
}
separator := p.tokens[p.position+1].Val
if separator != p.tokens[p.position+3].Val {
return time.Time{}, false, nil
}
// Determine the format based on the separators and numbers
var year, month, day int
switch separator {
case "-":
// ISO format: YYYY-MM-DD or D-M-YYYY
if len(p.tokens[p.position].Val) >= 4 {
year, month, day = firstNum, secondNum, thirdNum
// PHP doesn't support years > 9999 in YYYY-MM-DD format
if year > 9999 {
return time.Time{}, false, nil
}
} else if len(p.tokens[p.position+4].Val) >= 4 {
// D-M-YYYY (European style with dashes)
day, month, year = firstNum, secondNum, thirdNum
} else {
// Short year, try as Y-M-D
year, month, day = firstNum, secondNum, thirdNum
if year < 100 {
year = parseTwoDigitYear(year)
}
}
case "/":
// Could be YYYY/MM/DD or MM/DD/YYYY
if len(p.tokens[p.position].Val) >= 4 {
year, month, day = firstNum, secondNum, thirdNum
} else if len(p.tokens[p.position+4].Val) >= 4 {
month, day, year = firstNum, secondNum, thirdNum
} else {
return time.Time{}, false, nil
}
case ".":
// European format: DD.MM.YY or DD.MM.YYYY
day, month, year = firstNum, secondNum, thirdNum
// Handle 2-digit years
if year < 100 {
year = parseTwoDigitYear(year)
}
default:
return time.Time{}, false, nil
}
// Validate date components using our utility function
if !IsValidDate(year, month, day) {
return time.Time{}, false, NewInvalidDateError(year, month, day)
}
// Advance position past the parsed date
p.position += 5
return time.Date(year, time.Month(month), day, 0, 0, 0, 0, p.loc), true, nil
}
// tryParseNextLastExpression attempts to parse expressions like "next Monday" or "last year"
func (p *Parser) tryParseNextLastExpression() (time.Time, bool, error) {
if p.position >= len(p.tokens) {
return time.Time{}, false, nil
}
// Check for "next", "last", or "this"
token := p.tokens[p.position]
if token.Typ != TypeString || (token.Val != DirectionNext && token.Val != DirectionLast && token.Val != "this") {
return time.Time{}, false, nil
}
isNext := token.Val == DirectionNext
isThis := token.Val == "this"
p.position++
p.skipWhitespace()
// Check for the unit token
if p.position >= len(p.tokens) {
return time.Time{}, false, fmt.Errorf("%w after %s", ErrExpectedTimeUnit, token.Val)
}
unitToken := p.tokens[p.position]
if unitToken.Typ != TypeString {
return time.Time{}, false, fmt.Errorf("%w after %s, got %s", ErrExpectedTimeUnit, token.Val, unitToken.Val)
}
p.position++
// Handle special case: "next week" and "last week"
// PHP treats Monday as the first day of the week.
if unitToken.Val == UnitWeek {
if p.pd != nil {
// PHP represents "next/last/this week" as weekday=1 (Monday)
// plus a +/-7 day offset.
p.pd.SetRelativeWeekday(1)
if isNext {
p.pd.AddRelative(UnitDay, 7)
} else if !isThis {
p.pd.AddRelative(UnitDay, -7)
}
}
dayOfWeek := int(p.result.Weekday())
// Days since this week's Monday (Go weekday: 0=Sun,1=Mon,...,6=Sat)
daysSinceMonday := (dayOfWeek + 6) % 7
if isNext {
// Next week = next Monday (always 1-7 days ahead)
return p.result.AddDate(0, 0, 7-daysSinceMonday), true, nil
} else if isThis {
// This week = this Monday
return p.result.AddDate(0, 0, -daysSinceMonday), true, nil
} else {
// Last week = previous week's Monday (always 7-13 days back)
return p.result.AddDate(0, 0, -(daysSinceMonday + 7)), true, nil
}
}
// Check if it's a day of the week
dayNum := getDayOfWeek(unitToken.Val)
if dayNum >= 0 {
if p.pd != nil {
p.pd.SetRelativeWeekday(dayNum)
// PHP sets hour/minute/second to 0 for "next/last/this <weekday>".
p.pd.SetTime(0, 0, 0)
// "last <weekday>" adds a -7 day offset to the relative block.
if !isNext && !isThis {
p.pd.AddRelative(UnitDay, -7)
}
}
// Handle day of week
currentDay := int(p.result.Weekday())
if isThis {
// "this X" = the X of the current week (can be past or future)
daysUntil := (dayNum - currentDay + 7) % 7
targetDay := p.result.AddDate(0, 0, daysUntil)
year, month, day := targetDay.Date()
return time.Date(year, month, day, 0, 0, 0, 0, p.loc), true, nil
} else if isNext {
// "next X" = the upcoming occurrence of that day
daysUntil := (dayNum - currentDay + 7) % 7
if daysUntil == 0 {
daysUntil = 7 // If today is the target day, go to next week
}
nextDay := p.result.AddDate(0, 0, daysUntil)
year, month, day := nextDay.Date()
return time.Date(year, month, day, 0, 0, 0, 0, p.loc), true, nil
} else {
// Calculate days since the last occurrence
daysSince := (currentDay - dayNum + 7) % 7
if daysSince == 0 {
daysSince = 7 // If today is the target day, go to last week
}
lastDay := p.result.AddDate(0, 0, -daysSince)
year, month, day := lastDay.Date()
return time.Date(year, month, day, 0, 0, 0, 0, p.loc), true, nil
}
}
// Handle other time units
switch unitToken.Val {
case UnitDay:
if p.pd != nil {
p.pd.relative()
if isNext {
p.pd.AddRelative(UnitDay, 1)
} else if !isThis {
p.pd.AddRelative(UnitDay, -1)
}
}
if isNext {
return p.result.AddDate(0, 0, 1), true, nil
}
if isThis {
return p.result, true, nil
}
return p.result.AddDate(0, 0, -1), true, nil
case UnitMonth:
if p.pd != nil {
// PHP always emits the relative block for this/next/last X.
p.pd.relative()
if isNext {
p.pd.AddRelative(UnitMonth, 1)
} else if !isThis {
p.pd.AddRelative(UnitMonth, -1)
}
}
if isNext {
return p.result.AddDate(0, 1, 0), true, nil
} else {
return p.result.AddDate(0, -1, 0), true, nil
}
case UnitYear:
if p.pd != nil {
p.pd.relative()
if isNext {
p.pd.AddRelative(UnitYear, 1)
} else if !isThis {
p.pd.AddRelative(UnitYear, -1)
}
}
if isNext {
return p.result.AddDate(1, 0, 0), true, nil
} else {
return p.result.AddDate(-1, 0, 0), true, nil
}
case UnitHour, UnitMinute, UnitSecond:
if p.pd != nil {
p.pd.relative()
if isNext {
p.pd.AddRelative(unitToken.Val, 1)
} else if !isThis {
p.pd.AddRelative(unitToken.Val, -1)
}
}
if isNext {
return applyTimeOffset(p.result, 1, unitToken.Val), true, nil
}
if isThis {
return p.result, true, nil
}
return applyTimeOffset(p.result, -1, unitToken.Val), true, nil
default:
return time.Time{}, false, fmt.Errorf("%w: %s", ErrInvalidTimeUnit, unitToken.Val)
}
}
// daysInMonth returns the number of days in a given month and year
// isCompoundExpression checks if a string is a compound time expression (contains + or - in the middle)
func isCompoundExpression(str string) bool {
// Don't classify a numeric timezone suffix (+09:00, -0500) as a compound
// expression. A trailing " +HHMM" / " +HH:MM" / " -HHMM" is a TZ marker.
if idx := strings.LastIndexAny(str, "+-"); idx > 0 && str[idx-1] == ' ' {
tail := str[idx:]
if _, _, ok := parseNumericTimezoneOffset(tail); ok {
trimmed := strings.TrimSpace(str[:idx])
// If the prefix contains no other +/- in the middle, this isn't
// a compound expression.
if !containsInfixSign(trimmed) {
return false
}
}
}
// Normalize spaces around operators
spaceOperatorRe := strings.NewReplacer(" + ", "+", " - ", "-", "+ ", "+", "- ", "-")
normalizedStr := spaceOperatorRe.Replace(str)
// Check if we have + or - in the middle of the string (not at the start)
return (strings.Contains(normalizedStr, "+") && !strings.HasPrefix(normalizedStr, "+")) ||
(strings.Contains(normalizedStr, "-") && !strings.HasPrefix(normalizedStr, "-"))
}
// containsInfixSign reports whether s has a '+' or '-' after position 0.
func containsInfixSign(s string) bool {
for i := 1; i < len(s); i++ {
if s[i] == '+' || s[i] == '-' {
return true
}
}
return false
}
// parseDateWithRelativeTime parses a date followed by a relative time adjustment
// Examples: "2023-05-30 -1 month" or "2022-01-01 +1 year"
func parseDateWithRelativeTime(str string, now time.Time, loc *time.Location, opts []Option) (time.Time, bool) {
// Split on first whitespace to get date part and rest
datePart, timePart, ok := splitDateAndRest(str)
if !ok {
return time.Time{}, false
}
// Parse the date part
dateResult, err := StrToTime(datePart, append(opts, Rel(now))...)
if err != nil {
return time.Time{}, false
}
// Handle special case for month end dates when subtracting months
if timePart == "-1 month" {
year, month, day := dateResult.Date()
// Check if it's the last day of the month
if day == daysInMonth(year, month) {
// Create a date for the first day of the current month
firstOfMonth := time.Date(year, month, 1, 0, 0, 0, 0, loc)
// Subtract one day to get the last day of the previous month
prevMonth := firstOfMonth.AddDate(0, -1, 0)
// Get the last day of the previous month
lastDay := daysInMonth(prevMonth.Year(), prevMonth.Month())
// Create the final date with the last day of the previous month,
// preserving hour, minute, second from the original date
return time.Date(prevMonth.Year(), prevMonth.Month(), lastDay,
dateResult.Hour(), dateResult.Minute(), dateResult.Second(),
dateResult.Nanosecond(), loc), true
}
}
// Parse the time part using the date as reference
finalResult, err := StrToTime(timePart, append(opts, Rel(dateResult))...)
if err != nil {
return time.Time{}, false
}
return finalResult, true
}
// parseCompoundExpression parses a compound time expression like "next year+4 days"
func parseCompoundExpression(str string, now time.Time, opts []Option) (time.Time, error) {
// Normalize compound expressions like "next year+4 days" or "next year + 4 days"
// Replace spaces around + and - with nothing to make parsing easier
spaceOperatorRe := strings.NewReplacer(" + ", "+", " - ", "-", "+ ", "+", "- ", "-")
normalizedStr := spaceOperatorRe.Replace(str)
// Split the string at + and - operators
var parts []string
var operators []string
// Find all + and - operators (not at the beginning)
currentPart := ""
for i := 0; i < len(normalizedStr); i++ {
if (normalizedStr[i] == '+' || normalizedStr[i] == '-') && i > 0 {
parts = append(parts, currentPart)
operators = append(operators, string(normalizedStr[i]))
currentPart = ""
} else {
currentPart += string(normalizedStr[i])
}
}
// Add the last part
if currentPart != "" {
parts = append(parts, currentPart)
}
// Validate that we have at least one part and one operator
if len(parts) < 2 || len(operators) < 1 {
return time.Time{}, errors.New("invalid compound expression format")
}
// Process the first part
result, err := StrToTime(parts[0], append(opts, Rel(now))...)
if err != nil {
return time.Time{}, err
}
// Process each remaining part with its operator
for i := 0; i < len(operators); i++ {
// Check if we have a corresponding part for this operator
if i+1 >= len(parts) {
return time.Time{}, errors.New("missing operand after operator in compound expression")
}
// Apply the operator to the part
opPart := operators[i] + parts[i+1]
nextResult, err := StrToTime(opPart, append(opts, Rel(result))...)
if err != nil {
return time.Time{}, err
}
result = nextResult
}
return result, nil
}