Skip to content

Commit

Permalink
👔 up: timex - add some new consts and update the ParseRange() logic
Browse files Browse the repository at this point in the history
  • Loading branch information
inhere committed Jun 4, 2023
1 parent 0a10991 commit b6942a2
Show file tree
Hide file tree
Showing 3 changed files with 27 additions and 4 deletions.
11 changes: 7 additions & 4 deletions timex/timex.go
Expand Up @@ -19,15 +19,18 @@ const (
OneDaySec = 86400
OneWeekSec = 7 * 86400

Microsecond = time.Microsecond
Millisecond = time.Millisecond

Second = time.Second
Minute = time.Minute
OneMin = time.Minute
Hour = time.Hour
Minute = time.Minute
OneHour = time.Hour
Day = 24 * time.Hour
Hour = time.Hour
OneDay = 24 * time.Hour
Week = 7 * 24 * time.Hour
Day = OneDay
OneWeek = 7 * 24 * time.Hour
Week = OneWeek
)

// TimeX alias of Time
Expand Down
11 changes: 11 additions & 0 deletions timex/util.go
Expand Up @@ -130,8 +130,12 @@ type ParseRangeOpt struct {
// - False: "-1h" => "-1h,0"; "1h" => "+1h, feature"
// - True: "-1h" => "zero,-1h"; "1h" => "zero,1h"
OneAsEnd bool
// AutoSort is the option for sort the time range.
AutoSort bool
// SepChar is the separator char for time range string. default is '~'
SepChar byte
// BeforeFn hook for before parse time string.
BeforeFn func(string) string
// KeywordFn is the function for parse keyword time string.
KeywordFn func(string) (time.Time, time.Time, error)
}
Expand Down Expand Up @@ -200,7 +204,14 @@ func ParseRange(expr string, opt *ParseRangeOpt) (start, end time.Time, err erro

if s2 != "" {
end, err = TryToTime(s2, opt.BaseTime)
// auto sort range time
if opt.AutoSort && err == nil {
if !start.IsZero() && start.After(end) {
start, end = end, start
}
}
}

return
}

Expand Down
9 changes: 9 additions & 0 deletions timex/util_test.go
Expand Up @@ -274,4 +274,13 @@ func TestParseRange(t *testing.T) {
assert.Eq(t, timex.ZeroUnix, start.Unix())
assert.Eq(t, timex.ZeroUnix, end.Unix())
})

t.Run("auto sort", func(t *testing.T) {
opt := &timex.ParseRangeOpt{
AutoSort: true,
}
start, end, err := timex.ParseRange("2020-01-02 15:04:05~2020-01-01 15:04:05", opt)
assert.NoError(t, err)
assert.Gt(t, end.Unix(), start.Unix())
})
}

0 comments on commit b6942a2

Please sign in to comment.