Skip to content

Commit

Permalink
✨ feat: timex - add new func ElapsedNow and update the Elapsed() logic
Browse files Browse the repository at this point in the history
  • Loading branch information
inhere committed Jul 24, 2023
1 parent f0dea38 commit d6222f8
Show file tree
Hide file tree
Showing 5 changed files with 80 additions and 11 deletions.
34 changes: 23 additions & 11 deletions timex/conv.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,23 +2,34 @@ package timex

import (
"fmt"
"math"
"strconv"
"strings"
"time"

"github.com/gookit/goutil/internal/comfunc"
"github.com/gookit/goutil/strutil"
)

// Elapsed calc elapsed time from start time
func Elapsed(start time.Time) time.Duration {
return time.Since(start)
// Elapsed calc elapsed time from start time to end time.
func Elapsed(start, end time.Time) string {
dur := end.Sub(start)

switch {
case dur > time.Hour:
return fmt.Sprintf("%.2fhrs", dur.Hours())
case dur > time.Minute:
return fmt.Sprintf("%.2fmins", dur.Minutes())
case dur > time.Second:
return fmt.Sprintf("%.3fs", dur.Seconds())
case dur > time.Millisecond:
return fmt.Sprintf("%.2fms", float64(dur.Nanoseconds())/1e6)
default:
return fmt.Sprintf("%.2fµs", float64(dur.Nanoseconds())/1e3)
}
}

// ElapsedString calc elapsed time from start time. unit: ms
func ElapsedString(start time.Time) string {
return strconv.FormatInt(time.Since(start).Milliseconds(), 10)
// ElapsedNow calc elapsed time from start time to now.
func ElapsedNow(start time.Time) string {
return Elapsed(start, time.Now())
}

//
Expand Down Expand Up @@ -64,7 +75,7 @@ func FromNow(t time.Time) string {

// FromNowWith format time from now with custom TimeMessage list
func FromNowWith(u time.Time, tms []TimeMessage) string {
return HowLongAgo2(int64(time.Now().Sub(u).Seconds()), tms)
return HowLongAgo2(int64(time.Since(u).Seconds()), tms)
}

// HowLongAgo format diff time seconds to string. alias of HowLongAgo2()
Expand All @@ -91,7 +102,7 @@ func HowLongAgo2(diffSec int64, tms []TimeMessage) string {
if len(secs) == 1 {
return msg
}
return fmt.Sprintf(msg, int64(math.Ceil(float64(diffInt/secs[1]))))
return fmt.Sprintf(msg, int64(diffInt/secs[1]))
}

//
Expand Down Expand Up @@ -175,7 +186,8 @@ func ensureOpt(opt *ParseRangeOpt) *ParseRangeOpt {
}

// ParseRange parse time range expression string to time.Time range.
// - "0" is alias of "now"
//
// - "0" will use opt.BaseTime.
//
// Expression format:
//
Expand Down
38 changes: 38 additions & 0 deletions timex/conv_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,28 @@ import (
"github.com/gookit/goutil/timex"
)

func TestElapsedNow(t *testing.T) {
// hrs
st := time.Now().Add(-204 * time.Minute)
assert.Eq(t, "3.40hrs", timex.ElapsedNow(st))

// min
st = time.Now().Add(-184 * time.Second)
assert.Eq(t, "3.07mins", timex.ElapsedNow(st))

// s
st = time.Now().Add(-1204 * time.Millisecond)
assert.Eq(t, "1.204s", timex.ElapsedNow(st))

// ms
st = time.Now().Add(-204 * time.Millisecond)
assert.Eq(t, "204.00ms", timex.ElapsedNow(st))

// us
st = time.Now().Add(-2304 * time.Nanosecond)
assert.StrContains(t, timex.ElapsedNow(st), "2.4")
}

func TestFromNow(t *testing.T) {
lastIdx := len(timex.TimeMessages) - 1
for i, tm := range timex.TimeMessages {
Expand Down Expand Up @@ -106,6 +128,9 @@ func TestParseRange(t *testing.T) {
// invalid
{"~", timex.ZeroUnix, timex.ZeroUnix, false},
{" ", timex.ZeroUnix, timex.ZeroUnix, false},
{"invalid", timex.ZeroUnix, timex.ZeroUnix, false},
{"2invalid", timex.ZeroUnix, timex.ZeroUnix, false},
{"<= 2invalid", timex.ZeroUnix, timex.ZeroUnix, false},
}

bt, err := timex.FromDate("2023-01-02 15:04:05")
Expand Down Expand Up @@ -159,6 +184,19 @@ func TestParseRange(t *testing.T) {
assert.Eq(t, timex.ZeroUnix, end.Unix())
})

t.Run("keyword tomorrow", func(t *testing.T) {
td := timex.Now().DayAfter(1)
start, end, err := timex.ParseRange("tomorrow", nil)
assert.NoError(t, err)
assert.Eq(t, td.DayStart().Unix(), start.Unix())
assert.Eq(t, td.DayEnd().Unix(), end.Unix())

start, end, err = timex.ParseRange("~tomorrow", nil)
assert.Error(t, err)
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,
Expand Down
10 changes: 10 additions & 0 deletions timex/gotime_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -28,3 +28,13 @@ func TestAddSeconds(t *testing.T) {
nt = timex.AddMinutes(nw, 1)
assert.True(t, nt.After(nw))
}

func TestNowAddSec(t *testing.T) {
nw := time.Now()

nt := timex.NowAddSec(10)
assert.True(t, nt.After(nw))

nt = timex.NowAddSeconds(10)
assert.True(t, nt.After(nw))
}
1 change: 1 addition & 0 deletions timex/timex_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,7 @@ func TestTimeX_AddDay(t *testing.T) {
yd1 := tx.AddDay(-1)
assert.Eq(t, yd.Unix(), yd1.Unix())
assert.Eq(t, yd.Unix(), tx.DayAgo(1).Unix())
assert.Eq(t, yd.Unix(), tx.SubDay(1).Unix())

assert.Eq(t, "1 day", tx.HowLongAgo(yd.Time))

Expand Down
8 changes: 8 additions & 0 deletions timex/util_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -89,6 +89,7 @@ func TestToDur(t *testing.T) {
ok bool
}{
{"", time.Duration(0), false},
{"invalid", time.Duration(0), false},
{"0", time.Duration(0), true},
{"now", time.Duration(0), false},
{"3s", 3 * timex.Second, true},
Expand Down Expand Up @@ -121,11 +122,15 @@ func TestToDur(t *testing.T) {
dur, err = timex.ToDuration("0")
assert.NoErr(t, err)
assert.Eq(t, time.Duration(0), dur)
}

func TestIsDuration(t *testing.T) {
assert.True(t, timex.IsDuration("3s"))
assert.True(t, timex.IsDuration("3m"))
assert.True(t, timex.IsDuration("-3h"))
assert.True(t, timex.IsDuration("0"))

assert.False(t, timex.IsDuration("3invalid"))
}

func TestInRange(t *testing.T) {
Expand All @@ -134,10 +139,13 @@ func TestInRange(t *testing.T) {
out bool
}{
{"-5s", "5s", true},
{"-5s", "", true},
{"", "-2s", false},
{"", "", false},
}

now := time.Now()

for _, item := range tests {
startT, err := timex.TryToTime(item.start, now)
assert.NoErr(t, err)
Expand Down

0 comments on commit d6222f8

Please sign in to comment.