timex

package
v0.6.15 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jan 4, 2024 License: MIT Imports: 7 Imported by: 11

README

Timex

Provides an enhanced time.Time implementation, and add more commonly used functional methods.

Install

go get github.com/gookit/goutil/timex

Usage

Create timex instance
now := timex.Now()

// from time.Time
tx := timex.New(time.Now())
tx := timex.FromTime(time.Now())

// from time unix
tx := timex.FromUnix(1647411580)

Create from datetime string:

// auto match layout by datetime
tx, err  := timex.FromString("2022-04-20 19:40:34")
// custom set the datetime layout
tx, err  := timex.FromString("2022-04-20 19:40:34", "2006-01-02 15:04:05")
// use date template as layout
tx, err  := timex.FromDate("2022-04-20 19:40:34", "Y-m-d H:I:S")
Use timex instance
tx := timex.Now()

Change time:

tx.Yesterday()
tx.Tomorrow()

tx.DayStart() // get time at Y-m-d 00:00:00
tx.DayEnd() // get time at Y-m-d 23:59:59
tx.HourStart() // get time at Y-m-d H:00:00
tx.HourEnd() // get time at Y-m-d H:59:59

tx.AddDay(2)
tx.AddHour(1)
tx.AddMinutes(15)
tx.AddSeconds(120)

Compare time:

// before compare
tx.IsBefore(u time.Time)
tx.IsBeforeUnix(1647411580)
// after compare
tx.IsAfter(u time.Time)
tx.IsAfterUnix(1647411580)
Helper functions
ts := timex.NowUnix() // current unix timestamp

t := NowAddDay(1) // from now add 1 day
t := NowAddHour(1) // from now add 1 hour
t := NowAddMinutes(3) // from now add 3 minutes
t := NowAddSeconds(180) // from now add 180 seconds
Convert time to date by template

Template Chars:

 Y,y - year
  Y - year 2006
  y - year 06
 m - month 01-12
 d - day 01-31
 H,h - hour
  H - hour 00-23
  h - hour 01-12
 I,i - minute
  I - minute 00-59
  i - minute 0-59
 S,s - second
  S - second 00-59
  s - second 0-59
... ...

More, please see charMap

Examples, use timex format date:

tx := timex.Now()
date := tx.DateFormat("Y-m-d H:I:S") // Output: 2022-04-20 19:09:03
date = tx.DateFormat("y-m-d h:i:s") // Output: 22-04-20 07:9:3

Format time.Time:

tx := time.Now()
date := timex.DateFormat(tx, "Y-m-d H:I:S") // Output: 2022-04-20 19:40:34

More usage:

ts := timex.NowUnix() // current unix timestamp

date := FormatUnix(ts, "2006-01-02 15:04:05") // Get: 2022-04-20 19:40:34
date := FormatUnixByTpl(ts, "Y-m-d H:I:S") // Get: 2022-04-20 19:40:34

Functions

func AddDay(t time.Time, day int) time.Time
func AddHour(t time.Time, hour int) time.Time
func AddMinutes(t time.Time, minutes int) time.Time
func AddSeconds(t time.Time, seconds int) time.Time
func Date(t time.Time, template string) string
func DateFormat(t time.Time, template string) string
func DayEnd(t time.Time) time.Time
func DayStart(t time.Time) time.Time
func Format(t time.Time) string
func FormatBy(t time.Time, layout string) string
func FormatByTpl(t time.Time, template string) string
func FormatUnix(sec int64) string
func FormatUnixBy(sec int64, layout string) string
func FormatUnixByTpl(sec int64, template string) string
func HourEnd(t time.Time) time.Time
func HourStart(t time.Time) time.Time
func HowLongAgo(sec int64) string
func NowAddDay(day int) time.Time
func NowAddHour(hour int) time.Time
func NowAddMinutes(minutes int) time.Time
func NowAddSeconds(seconds int) time.Time
func NowHourEnd() time.Time
func NowHourStart() time.Time
func NowUnix() int64
func SetLocalByName(tzName string) error
func ToDuration(s string) (time.Duration, error)
func ToLayout(template string) string
func TodayEnd() time.Time
func TodayStart() time.Time

// for create timex.Time
    func FromDate(s string, template ...string) (*Time, error)
    func FromString(s string, layouts ...string) (*Time, error)
    func FromTime(t time.Time) *Time
    func FromUnix(sec int64) *Time
    func Local() *Time
    func LocalByName(tzName string) *Time
    func New(t time.Time) *Time
    func Now() *Time
    func Wrap(t time.Time) *Time
Methods in timex.Time
func (t *Time) AddDay(day int) *Time
func (t *Time) AddHour(hours int) *Time
func (t *Time) AddMinutes(minutes int) *Time
func (t *Time) AddSeconds(seconds int) *Time
func (t *Time) CustomHMS(hour, min, sec int) *Time
func (t *Time) DateFormat(template string) string
func (t *Time) Datetime() string
func (t *Time) DayAfter(day int) *Time
func (t *Time) DayAgo(day int) *Time
func (t *Time) DayEnd() *Time
func (t *Time) DayStart() *Time
func (t Time) Diff(u time.Time) time.Duration
func (t Time) DiffSec(u time.Time) int
func (t *Time) Format(layout string) string
func (t *Time) HourEnd() *Time
func (t *Time) HourStart() *Time
func (t Time) HowLongAgo(before time.Time) string
func (t *Time) IsAfter(u time.Time) bool
func (t *Time) IsAfterUnix(ux int64) bool
func (t *Time) IsBefore(u time.Time) bool
func (t *Time) IsBeforeUnix(ux int64) bool
func (t *Time) SubDay(day int) *Time
func (t *Time) SubHour(hours int) *Time
func (t *Time) SubMinutes(minutes int) *Time
func (t *Time) SubSeconds(seconds int) *Time
func (t Time) SubUnix(u time.Time) int
func (t Time) T() time.Time
func (t Time) Timestamp() int64
func (t *Time) Tomorrow() *Time
func (t *Time) TplFormat(template string) string
func (t *Time) UnmarshalJSON(data []byte) error
func (t *Time) UnmarshalText(data []byte) error
func (t *Time) Yesterday() *Time

Code Check & Testing

gofmt -w -l ./
golint ./...

Testing:

go test -v ./timex/...

Test limit by regexp:

go test -v -run ^TestSetByKeys ./timex/...

Documentation

Overview

Package timex provides an enhanced time.Time implementation. Add more commonly used functional methods.

such as: DayStart(), DayAfter(), DayAgo(), DateFormat() and more.

Index

Constants

View Source
const (
	DatetimeLayout = "2006-01-02 15:04:05"
	LayoutWithMs3  = "2006-01-02 15:04:05.000"
	LayoutWithMs6  = "2006-01-02 15:04:05.000000"
	DateOnlyLayout = "2006-01-02"
	TimeOnlyLayout = "15:04:05"

	// ZeroUnix zero unix timestamp
	ZeroUnix int64 = -62135596800
)

some time layout or time

View Source
const (
	DefaultTemplate = "Y-m-d H:I:S"   // equals layout: "2006-01-02 15:04:05"
	TemplateWithMs3 = "Y-m-d H:I:S.v" // end with ".000"
	TemplateWithMs6 = "Y-m-d H:I:S.u" // end with ".000000"
)

some common datetime templates

View Source
const (
	OneSecond   = 1
	OneMinSec   = 60
	OneHourSec  = 3600
	OneDaySec   = 86400
	OneWeekSec  = 7 * 86400
	OneMonthSec = 30 * 86400

	Microsecond = time.Microsecond
	Millisecond = time.Millisecond

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

provide some commonly time consts

Variables

View Source
var (
	// DefaultLayout template for format time
	DefaultLayout = DatetimeLayout
	// ZeroTime zero time instance
	ZeroTime = time.Time{}
)
View Source
var TimeMessages = []TimeMessage{
	{"< 1 sec ago", []int{0}},
	{"1 sec ago", []int{1}},
	{"%d secs ago", []int{45, 1}},
	{"1 min ago", []int{89}},
	{"%d mins ago", []int{44 * 60, 60}},
	{"1 hour ago", []int{89 * 60}},
	{"%d hours ago", []int{21 * 3600, 3600}},
	{"1 day ago", []int{35 * 3600}},
	{"%d days ago", []int{30 * 86400, 86400}},

	{"1 month ago", []int{45 * 86400}},
	{"%d months ago", []int{319 * 86400, 2592000}},
	{"1 year ago", []int{547 * 86400}},
	{"%d years ago", []int{547 * 86400, 12 * 2592000}},
}

TimeMessages time message list.

NOTE: last item.Seconds[0] is min boundary value.

Functions

func AddDay

func AddDay(t time.Time, day int) time.Time

AddDay add some day time for given time

func AddHour

func AddHour(t time.Time, hour int) time.Time

AddHour add some hour time for given time

func AddMinutes

func AddMinutes(t time.Time, minutes int) time.Time

AddMinutes add some minutes time for given time

func AddSec added in v0.6.9

func AddSec(t time.Time, seconds int) time.Time

AddSec add some seconds time for given time. alias of AddSeconds()

func AddSeconds

func AddSeconds(t time.Time, seconds int) time.Time

AddSeconds add some seconds time for given time

func Date added in v0.5.1

func Date(t time.Time, template ...string) string

Date format time by given date template. see ToLayout() for template parse.

func DateFormat added in v0.5.1

func DateFormat(t time.Time, template string) string

DateFormat format time by given date template. see ToLayout()

func Datetime added in v0.6.9

func Datetime(t time.Time, template ...string) string

Datetime convert time to string use template. see ToLayout() for template parse.

func DayEnd added in v0.5.1

func DayEnd(t time.Time) time.Time

DayEnd time for given time

func DayStart added in v0.5.1

func DayStart(t time.Time) time.Time

DayStart time for given time

func Elapsed added in v0.6.11

func Elapsed(start, end time.Time) string

Elapsed calc elapsed time from start time to end time.

func ElapsedNow added in v0.6.12

func ElapsedNow(start time.Time) string

ElapsedNow calc elapsed time from start time to now.

func Format

func Format(t time.Time) string

Format convert time to string use default layout

func FormatBy

func FormatBy(t time.Time, layout string) string

FormatBy given default layout

func FormatByTpl added in v0.5.1

func FormatByTpl(t time.Time, template string) string

FormatByTpl format time by given date template. see ToLayout()

func FormatUnix

func FormatUnix(sec int64, layout ...string) string

FormatUnix time seconds use default layout

func FormatUnixBy

func FormatUnixBy(sec int64, layout string) string

FormatUnixBy format time seconds use given layout

func FormatUnixByTpl added in v0.5.1

func FormatUnixByTpl(sec int64, template ...string) string

FormatUnixByTpl format time seconds use given date template. see ToLayout()

func FromNow added in v0.6.11

func FromNow(t time.Time) string

FromNow format time from now, returns like: 1 hour ago, 2 days ago

refer: https://gist.github.com/davidrleonard/259fe449b1ec13bf7d87cde567ca0fde

func FromNowWith added in v0.6.11

func FromNowWith(u time.Time, tms []TimeMessage) string

FromNowWith format time from now with custom TimeMessage list

func HourEnd added in v0.5.2

func HourEnd(t time.Time) time.Time

HourEnd time for given time

func HourStart added in v0.5.1

func HourStart(t time.Time) time.Time

HourStart time for given time

func HowLongAgo added in v0.5.1

func HowLongAgo(diffSec int64) string

HowLongAgo format diff time seconds to string. alias of HowLongAgo2()

func HowLongAgo2 added in v0.6.11

func HowLongAgo2(diffSec int64, tms []TimeMessage) string

HowLongAgo2 format diff time seconds with custom TimeMessage list

func InRange added in v0.6.9

func InRange(dst, start, end time.Time) bool

InRange check the dst time is in the range of start and end.

if start is zero, only check dst < end, if end is zero, only check dst > start.

func IsDuration added in v0.6.9

func IsDuration(s string) bool

IsDuration check the string is a valid duration string. alias of comfunc.IsDuration()

func NowAddDay

func NowAddDay(day int) time.Time

NowAddDay add some day time from now

func NowAddHour

func NowAddHour(hour int) time.Time

NowAddHour add some hour time from now

func NowAddMinutes

func NowAddMinutes(minutes int) time.Time

NowAddMinutes add some minutes time from now

func NowAddSec added in v0.6.9

func NowAddSec(seconds int) time.Time

NowAddSec add some seconds time from now. alias of NowAddSeconds()

func NowAddSeconds

func NowAddSeconds(seconds int) time.Time

NowAddSeconds add some seconds time from now

func NowDate added in v0.6.13

func NowDate(template ...string) string

NowDate quick get current date string. if template is empty, will use DefaultTemplate.

func NowHourEnd added in v0.5.5

func NowHourEnd() time.Time

NowHourEnd time

func NowHourStart added in v0.5.1

func NowHourStart() time.Time

NowHourStart time

func NowUnix

func NowUnix() int64

NowUnix is short of time.Now().Unix()

func ParseRange added in v0.6.9

func ParseRange(expr string, opt *ParseRangeOpt) (start, end time.Time, err error)

ParseRange parse time range expression string to time.Time range.

  • "0" will use opt.BaseTime.

Expression format:

"-5h~-1h"       	=> 5 hours ago to 1 hour ago
"1h~5h"         	=> 1 hour after to 5 hours after
"-1h~1h"        	=> 1 hour ago to 1 hour after
"-1h"            	=> 1 hour ago to feature. eq "-1h~"
"-1h~0"          	=> 1 hour ago to now.
"< -1h" OR "~-1h"   => 1 hour ago.
"> 1h" OR "1h"     	=> 1 hour after to feature
// keyword: now, today, yesterday, tomorrow
"today"          => today start to today end
"yesterday"      => yesterday start to yesterday end
"tomorrow"       => tomorrow start to tomorrow end

Usage:

start, end, err := ParseRange("-1h~1h", nil)
if err != nil {
	log.Fatal(err)
}
fmt.Println(start, end)

func SetLocalByName

func SetLocalByName(tzName string) error

SetLocalByName set local by tz name. eg: UTC, PRC

func ToDur added in v0.6.9

func ToDur(s string) (time.Duration, error)

ToDur parse a duration string. alias of ToDuration()

func ToDuration added in v0.5.6

func ToDuration(s string) (time.Duration, error)

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 ToLayout added in v0.5.1

func ToLayout(template string) string

ToLayout convert chars date template to Go date layout.

template chars see timex.charMap

func ToTime added in v0.6.9

func ToTime(s string, layouts ...string) (time.Time, error)

ToTime parse a datetime string. alias of strutil.ToTime()

func TodayEnd added in v0.5.1

func TodayEnd() time.Time

TodayEnd time

func TodayStart added in v0.5.1

func TodayStart() time.Time

TodayStart time

func TryToTime added in v0.6.9

func TryToTime(s string, bt time.Time) (time.Time, error)

TryToTime parse a date string or duration string to time.Time.

if s is empty, return zero time.

Types

type ParseRangeOpt added in v0.6.9

type ParseRangeOpt struct {
	// BaseTime is the base time for relative time string.
	// if is zero, use time.Now() as base time.
	BaseTime time.Time
	// OneAsEnd is the option for one time range.
	//  - 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)
}

ParseRangeOpt is the option for ParseRange

type Time added in v0.5.13

type Time struct {
	time.Time
	// Layout set the default date format layout. default use DefaultLayout
	Layout string
}

Time an enhanced time.Time implementation.

func FromDate added in v0.5.2

func FromDate(s string, template ...string) (*Time, error)

FromDate create from datetime string.

func FromString added in v0.5.1

func FromString(s string, layouts ...string) (*Time, error)

FromString create from datetime string. see strutil.ToTime()

func FromTime added in v0.5.2

func FromTime(t time.Time) *Time

FromTime new instance form given time.Time. alias of the New()

func FromUnix added in v0.5.1

func FromUnix(sec int64) *Time

FromUnix create from unix time

func Local

func Local() *Time

Local time for now

func LocalByName

func LocalByName(tzName string) *Time

LocalByName time for now

func New added in v0.5.1

func New(t time.Time) *Time

New instance form given time

func Now

func Now() *Time

Now time instance

func Wrap added in v0.5.2

func Wrap(t time.Time) *Time

Wrap the go time instance. alias of the New()

func (*Time) AddDay added in v0.5.13

func (t *Time) AddDay(day int) *Time

AddDay add some day time for the time

func (*Time) AddDur added in v0.6.9

func (t *Time) AddDur(dur time.Duration) *Time

AddDur some duration time

func (*Time) AddHour added in v0.5.13

func (t *Time) AddHour(hours int) *Time

AddHour add some hour time

func (*Time) AddMinutes added in v0.5.13

func (t *Time) AddMinutes(minutes int) *Time

AddMinutes add some minutes time for the time

func (*Time) AddSeconds added in v0.5.13

func (t *Time) AddSeconds(seconds int) *Time

AddSeconds add some seconds time the time

func (*Time) AddString added in v0.6.9

func (t *Time) AddString(dur string) *Time

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 (*Time) CustomHMS added in v0.5.13

func (t *Time) CustomHMS(hour, min, sec int) *Time

CustomHMS custom change the hour, minute, second for create new time.

func (*Time) DateFormat added in v0.5.13

func (t *Time) DateFormat(template string) string

DateFormat use input template format time to date.

Example:

tn := timex.Now()
tn.DateFormat("Y-m-d H:i:s") // Output: 2019-01-01 12:12:12
tn.DateFormat("Y-m-d H:i") // Output: 2019-01-01 12:12
tn.DateFormat("Y-m-d") // Output: 2019-01-01
tn.DateFormat("Y-m") // Output: 2019-01
tn.DateFormat("y-m-d") // Output: 19-01-01
tn.DateFormat("ymd") // Output: 190101

see ToLayout() for convert template to layout.

func (*Time) Datetime added in v0.5.13

func (t *Time) Datetime() string

Datetime use DefaultLayout format time to date. see Format()

func (*Time) DayAfter added in v0.5.13

func (t *Time) DayAfter(day int) *Time

DayAfter get some day after time for the time. alias of Time.AddDay()

func (*Time) DayAgo added in v0.5.13

func (t *Time) DayAgo(day int) *Time

DayAgo get some day ago time for the time

func (*Time) DayEnd added in v0.5.13

func (t *Time) DayEnd() *Time

DayEnd get time at 23:59:59

func (*Time) DayStart added in v0.5.13

func (t *Time) DayStart() *Time

DayStart get time at 00:00:00

func (Time) Diff added in v0.5.13

func (t Time) Diff(u time.Time) time.Duration

Diff calc diff duration for t - u. alias of time.Time.Sub()

func (Time) DiffSec added in v0.5.13

func (t Time) DiffSec(u time.Time) int

DiffSec calc diff seconds for t - u

func (Time) DiffUnix added in v0.6.0

func (t Time) DiffUnix(u int64) int

DiffUnix calc diff seconds for t.Unix() - u

func (*Time) Format added in v0.5.13

func (t *Time) Format(layout string) string

Format returns a textual representation of the time value formatted according to the layout defined by the argument.

see time.Time.Format()

func (*Time) HourEnd added in v0.5.13

func (t *Time) HourEnd() *Time

HourEnd time

func (*Time) HourStart added in v0.5.13

func (t *Time) HourStart() *Time

HourStart time

func (Time) HowLongAgo added in v0.5.13

func (t Time) HowLongAgo(before time.Time) string

HowLongAgo format diff time to string.

func (*Time) IsAfter added in v0.5.13

func (t *Time) IsAfter(u time.Time) bool

IsAfter the given time

func (*Time) IsAfterUnix added in v0.5.13

func (t *Time) IsAfterUnix(ux int64) bool

IsAfterUnix the given unix timestamp

func (*Time) IsBefore added in v0.5.13

func (t *Time) IsBefore(u time.Time) bool

IsBefore the given time

func (*Time) IsBeforeUnix added in v0.5.13

func (t *Time) IsBeforeUnix(ux int64) bool

IsBeforeUnix the given unix timestamp

func (*Time) SubDay added in v0.5.13

func (t *Time) SubDay(day int) *Time

SubDay add some day time for the time

func (*Time) SubHour added in v0.5.13

func (t *Time) SubHour(hours int) *Time

SubHour minus some hour time

func (*Time) SubMinutes added in v0.5.13

func (t *Time) SubMinutes(minutes int) *Time

SubMinutes minus some minutes time for the time

func (*Time) SubSeconds added in v0.5.13

func (t *Time) SubSeconds(seconds int) *Time

SubSeconds minus some seconds time the time

func (Time) SubUnix added in v0.5.13

func (t Time) SubUnix(u time.Time) int

SubUnix calc diff seconds for t - u

func (Time) T added in v0.5.13

func (t Time) T() time.Time

T returns the t.Time

func (Time) Timestamp added in v0.5.13

func (t Time) Timestamp() int64

Timestamp value. alias of t.Unix()

func (*Time) Tomorrow added in v0.5.13

func (t *Time) Tomorrow() *Time

Tomorrow time. get tomorrow time for the time

func (*Time) TplFormat added in v0.5.13

func (t *Time) TplFormat(template string) string

TplFormat use input template format time to date.

alias of DateFormat()

func (*Time) UnmarshalJSON added in v0.5.13

func (t *Time) UnmarshalJSON(data []byte) error

UnmarshalJSON implements the json.Unmarshaler interface.

Tip: will auto match a format by strutil.ToTime()

func (*Time) UnmarshalText added in v0.5.13

func (t *Time) UnmarshalText(data []byte) error

UnmarshalText implements the encoding.TextUnmarshaler interface.

Tip: will auto match a format by strutil.ToTime()

func (*Time) Yesterday added in v0.5.13

func (t *Time) Yesterday() *Time

Yesterday get day ago time for the time

type TimeMessage added in v0.6.11

type TimeMessage struct {
	// Message string or format string
	Message string
	// Seconds time range.
	// first elem is max boundary value, second elem is divisor(unit).
	Seconds []int
}

TimeMessage struct for HowLongAgo2(), FromNowWith()

type TimeX

type TimeX = Time

TimeX alias of Time Deprecated: use Time instead

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL