-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtime_parser.go
More file actions
71 lines (60 loc) · 1.83 KB
/
time_parser.go
File metadata and controls
71 lines (60 loc) · 1.83 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
package main
import (
"time"
"github.com/markusmobius/go-dateparser"
)
func parseTime(timeStr string) (time.Time, error) {
// Try standard Go time formats first for well-formed ISO dates
formats := []string{
time.RFC3339,
time.RFC3339Nano,
"2006-01-02 15:04:05",
"2006-01-02 15:04",
"2006-01-02",
time.RFC1123,
time.RFC1123Z,
}
for _, format := range formats {
parsedTime, parseErr := time.Parse(format, timeStr)
if parseErr == nil {
// Convert to local timezone
return parsedTime.Local(), nil
}
}
// If standard formats fail, use dateparser for natural language
configuration := &dateparser.Configuration{
CurrentTime: time.Now(),
DateOrder: dateparser.DMY,
PreferredDateSource: dateparser.Future,
}
date, err := dateparser.Parse(configuration, timeStr)
if err != nil {
return time.Time{}, err
}
// If the parsed time is in the past, try adding "in" prefix
if time.Now().After(date.Time) {
dateWithIn, errIn := dateparser.Parse(configuration, "in "+timeStr)
if errIn == nil && time.Now().Before(dateWithIn.Time) {
// Convert to local timezone
return dateWithIn.Time.Local(), nil
}
}
// If still in the past, try adding "on" prefix for weekday names
if time.Now().After(date.Time) {
dateWithOn, errOn := dateparser.Parse(configuration, "on "+timeStr)
if errOn == nil && time.Now().Before(dateWithOn.Time) {
// Convert to local timezone
return dateWithOn.Time.Local(), nil
}
}
// If still in the past, try "next" prefix for weekday names
if time.Now().After(date.Time) {
dateWithNext, errNext := dateparser.Parse(configuration, "next "+timeStr)
if errNext == nil && time.Now().Before(dateWithNext.Time) {
// Convert to local timezone
return dateWithNext.Time.Local(), nil
}
}
// Convert to local timezone before returning
return date.Time.Local(), err
}