Skip to content

Commit

Permalink
✨ feat: timex - add new util func NowAddSec(), IsDuration(), InRange()
Browse files Browse the repository at this point in the history
- time string parse func TryToTime(), ParseRange()
- add method Time.AddDur(), Time.AddString()
  • Loading branch information
inhere committed May 30, 2023
1 parent d3c8d4b commit ea05a1e
Show file tree
Hide file tree
Showing 6 changed files with 477 additions and 111 deletions.
20 changes: 20 additions & 0 deletions internal/comfunc/comfunc.go
Expand Up @@ -5,6 +5,7 @@ import (
"os"
"regexp"
"strings"
"time"
)

// Environ like os.Environ, but will returns key-value map[string]string data.
Expand Down Expand Up @@ -100,3 +101,22 @@ func FormatTplAndArgs(fmtAndArgs []any) string {
}
return fmt.Sprint(fmtAndArgs...)
}

var durStrReg = regexp.MustCompile(`^(-?\d+)(ns|us|µs|ms|s|m|h)$`)

// IsDuration check the string is a duration string.
func IsDuration(s string) bool {
if s == "0" {
return true
}
return durStrReg.MatchString(s)
}

// ToDuration parses a duration string. such as "300ms", "-1.5h" or "2h45m".
// Valid time units are "ns", "us" (or "µs"), "ms", "s", "m", "h".
func ToDuration(s string) (time.Duration, error) {
if s == "now" {
return 0, nil
}
return time.ParseDuration(s)
}
108 changes: 108 additions & 0 deletions timex/gotime.go
@@ -0,0 +1,108 @@
package timex

import "time"

// SetLocalByName set local by tz name. eg: UTC, PRC
func SetLocalByName(tzName string) error {
location, err := time.LoadLocation(tzName)
if err != nil {
return err
}

time.Local = location
return nil
}

// NowAddDay add some day time from now
func NowAddDay(day int) time.Time {
return time.Now().AddDate(0, 0, day)
}

// NowAddHour add some hour time from now
func NowAddHour(hour int) time.Time {
return time.Now().Add(time.Duration(hour) * OneHour)
}

// NowAddMinutes add some minutes time from now
func NowAddMinutes(minutes int) time.Time {
return time.Now().Add(time.Duration(minutes) * OneMin)
}

// NowAddSec add some seconds time from now. alias of NowAddSeconds()
func NowAddSec(seconds int) time.Time {
return time.Now().Add(time.Duration(seconds) * time.Second)
}

// NowAddSeconds add some seconds time from now
func NowAddSeconds(seconds int) time.Time {
return time.Now().Add(time.Duration(seconds) * time.Second)
}

// NowHourStart time
func NowHourStart() time.Time {
return HourStart(time.Now())
}

// NowHourEnd time
func NowHourEnd() time.Time {
return HourEnd(time.Now())
}

// AddDay add some day time for given time
func AddDay(t time.Time, day int) time.Time {
return t.AddDate(0, 0, day)
}

// AddHour add some hour time for given time
func AddHour(t time.Time, hour int) time.Time {
return t.Add(time.Duration(hour) * OneHour)
}

// AddMinutes add some minutes time for given time
func AddMinutes(t time.Time, minutes int) time.Time {
return t.Add(time.Duration(minutes) * OneMin)
}

// AddSeconds add some seconds time for given time
func AddSeconds(t time.Time, seconds int) time.Time {
return t.Add(time.Duration(seconds) * time.Second)
}

// AddSec add some seconds time for given time. alias of AddSeconds()
func AddSec(t time.Time, seconds int) time.Time {
return t.Add(time.Duration(seconds) * time.Second)
}

// HourStart time for given time
func HourStart(t time.Time) time.Time {
y, m, d := t.Date()
return time.Date(y, m, d, t.Hour(), 0, 0, 0, t.Location())
}

// HourEnd time for given time
func HourEnd(t time.Time) time.Time {
y, m, d := t.Date()
return time.Date(y, m, d, t.Hour(), 59, 59, int(time.Second-time.Nanosecond), t.Location())
}

// DayStart time for given time
func DayStart(t time.Time) time.Time {
y, m, d := t.Date()
return time.Date(y, m, d, 0, 0, 0, 0, t.Location())
}

// DayEnd time for given time
func DayEnd(t time.Time) time.Time {
y, m, d := t.Date()
return time.Date(y, m, d, 23, 59, 59, int(time.Second-time.Nanosecond), t.Location())
}

// TodayStart time
func TodayStart() time.Time {
return DayStart(time.Now())
}

// TodayEnd time
func TodayEnd() time.Time {
return DayEnd(time.Now())
}
15 changes: 11 additions & 4 deletions timex/template.go
Expand Up @@ -6,6 +6,13 @@ import (
"github.com/gookit/goutil/strutil"
)

// some common datetime templates
const (
DefaultTemplate = "Y-m-d H:i:s"
TemplateWithMs3 = "Y-m-d H:i:s.v" // end with ".000"
TemplateWithMs6 = "Y-m-d H:i:s.u" // end with ".000000"
)

// char to Go date layout
// eg: "Y-m-d H:i:s" => "2006-01-02 15:04:05",
//
Expand Down Expand Up @@ -41,10 +48,10 @@ var charMap = map[byte][]byte{
'S': []byte("05"), // 00 to 59
's': []byte("5"), // 0 to 59
// Time
'a': []byte("pm"), // am or pm
'A': []byte("PM"), // AM or PM
'v': []byte(".000"), // Milliseconds eg: 654
'u': []byte(".000000"), // Microseconds eg: 654321
'a': []byte("pm"), // am or pm
'A': []byte("PM"), // AM or PM
'v': []byte("000"), // Milliseconds eg: 654
'u': []byte("000000"), // Microseconds eg: 654321
// Timezone
'e': []byte("MST"), // Timezone identifier. eg: UTC, GMT, Atlantic/Azores
'Z': []byte("Z07"), // Timezone abbreviation, if known; otherwise the GMT offset. Examples: EST, MDT, +05
Expand Down
31 changes: 28 additions & 3 deletions timex/timex.go
Expand Up @@ -7,7 +7,7 @@ package timex
import (
"time"

"github.com/gookit/goutil/fmtutil"
"github.com/gookit/goutil/basefn"
"github.com/gookit/goutil/strutil"
)

Expand All @@ -33,6 +33,8 @@ const (
var (
// DefaultLayout template for format time
DefaultLayout = "2006-01-02 15:04:05"
// ZeroTime zero time instance
ZeroTime = time.Time{}
)

// TimeX alias of Time
Expand Down Expand Up @@ -187,6 +189,29 @@ func (t *Time) DayAfter(day int) *Time {
return t.AddDay(day)
}

// AddDur some duration time
func (t *Time) AddDur(dur time.Duration) *Time {
return &Time{
Time: t.Add(dur),
Layout: DefaultLayout,
}
}

// AddString add duration time string.
//
// Example:
//
// tn := timex.Now() // example as "2019-01-01 12:12:12"
// nt := tn.AddString("1h")
// nt.Datetime() // Output: 2019-01-01 13:12:12
func (t *Time) AddString(dur string) *Time {
d, err := ToDuration(dur)
if err != nil {
panic(err)
}
return t.AddDur(d)
}

// AddHour add some hour time
func (t *Time) AddHour(hours int) *Time {
return t.AddSeconds(hours * OneHourSec)
Expand Down Expand Up @@ -306,14 +331,14 @@ func (t *Time) IsAfterUnix(ux int64) bool {
return t.After(time.Unix(ux, 0))
}

// Timestamp value. alias t.Unix()
// Timestamp value. alias of t.Unix()
func (t Time) Timestamp() int64 {
return t.Unix()
}

// HowLongAgo format diff time to string.
func (t Time) HowLongAgo(before time.Time) string {
return fmtutil.HowLongAgo(t.Unix() - before.Unix())
return basefn.HowLongAgo(t.Unix() - before.Unix())
}

// UnmarshalJSON implements the json.Unmarshaler interface.
Expand Down

0 comments on commit ea05a1e

Please sign in to comment.