Skip to content

Import path: gitlab.soludian.com/soludian/fountain/libs/base/time_util

time_util

go
import "gitlab.soludian.com/soludian/fountain/libs/base/time_util"

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

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

Index

Constants

some common date time templates

go
const (
    KDefaultTemplate = "Y-m-d H:i:s"
    KTemplateWithMs3 = "Y-m-d H:i:s.v" // end with ".000"
    KTemplateWithMs6 = "Y-m-d H:i:s.u" // end with ".000000"
)

some time layout or time

go
const (
    KDateTimeLayout       = "2006-01-02 15:04:05"
    KLayoutWithMs3        = "2006-01-02 15:04:05.000"
    KLayoutWithMs6        = "2006-01-02 15:04:05.000000"
    KDateOnlyLayout       = "2006-01-02"
    KTimeOnlyLayout       = "15:04:05"
    KDateTimeAtFullLayout = "Monday, 02 January 2006 15:04:05 Z07:00"

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

provide some commonly time consts

go
const (
    KOneSecond   = 1
    KOneMinSec   = 60
    KOneHourSec  = 3600
    KOneDaySec   = 86400
    KOneWeekSec  = 7 * 86400
    KOneMonthSec = 30 * 86400

    KMicrosecond = time.Microsecond
    KMillisecond = time.Millisecond

    KSecond  = time.Second
    KOneMin  = time.Minute
    KMinute  = time.Minute
    KOneHour = time.Hour
    KHour    = time.Hour
    KOneDay  = 24 * time.Hour
    KDay     = KOneDay
    KOneWeek = 7 * 24 * time.Hour
    KWeek    = KOneWeek
    KMonth   = 30 * 24 * time.Hour
)

Variables

go
var (
    // DefaultLayout template for format time
    DefaultLayout = KDateTimeLayout
    // ZeroTime zero time instance
    ZeroTime = time.Time{}
)

TimeMessages time message list.

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

go
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}},
}

func AddDay

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

AddDay add some day time for given time

func AddHour

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

AddHour add some hour time for given time

func AddMinutes

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

AddMinutes add some minutes time for given time

func AddSec

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

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

func AddSeconds

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

AddSeconds add some seconds time for given time

func Date

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

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

func DateFormat

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

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

func Datetime

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

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

func DayEnd

go
func DayEnd(t time.Time) time.Time

DayEnd time for given time

func DayStart

go
func DayStart(t time.Time) time.Time

DayStart time for given time

func Elapsed

go
func Elapsed(start, end time.Time) string

Elapsed calc elapsed time from start time to end time.

func ElapsedNow

go
func ElapsedNow(start time.Time) string

ElapsedNow calc elapsed time from start time to now.

func Format

go
func Format(t time.Time) string

Format convert time to string use default layout

func FormatBy

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

FormatBy given default layout

func FormatByTpl

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

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

func FormatUnix

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

FormatUnix time seconds use default layout

func FormatUnixBy

go
func FormatUnixBy(sec int64, layout string) string

FormatUnixBy format time seconds use given layout

func FormatUnixByTpl

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

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

func FromNow

go
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

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

FromNowWith format time from now with custom TimeMessage list

func HourEnd

go
func HourEnd(t time.Time) time.Time

HourEnd time for given time

func HourStart

go
func HourStart(t time.Time) time.Time

HourStart time for given time

func HowLongAgo

go
func HowLongAgo(diffSec int64) string

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

func HowLongAgo2

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

HowLongAgo2 format diff time seconds with custom TimeMessage list

func InRange

go
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

go
func IsDuration(s string) bool

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

func MustToDur

go
func MustToDur(s string) time.Duration

MustToDur parse a duration string. alias of SafeToDuration()

func MustToDuration

go
func MustToDuration(s string) time.Duration

SafeToDuration parses a duration string. such as "300ms", "-1.5h" or "2h45m". Valid time units are "ns", "us" (or "µs"), "ms", "s", "m", "h". Panic if error

func NowAddDay

go
func NowAddDay(day int) time.Time

NowAddDay add some day time from now

func NowAddHour

go
func NowAddHour(hour int) time.Time

NowAddHour add some hour time from now

func NowAddMinutes

go
func NowAddMinutes(minutes int) time.Time

NowAddMinutes add some minutes time from now

func NowAddSec

go
func NowAddSec(seconds int) time.Time

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

func NowAddSeconds

go
func NowAddSeconds(seconds int) time.Time

NowAddSeconds add some seconds time from now

func NowHourEnd

go
func NowHourEnd() time.Time

NowHourEnd time

func NowHourStart

go
func NowHourStart() time.Time

NowHourStart time

func NowUnix

go
func NowUnix() int64

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

func NowUnix32

go
func NowUnix32() int32

NowUnix32 is short of time.Now().Unix() with int32 rounding

func ParseRange

go
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 SafeToDur

go
func SafeToDur(s string) time.Duration

SafeToDur parse a duration string. alias of SafeToDuration()

func SafeToDuration

go
func SafeToDuration(s string) time.Duration

SafeToDuration parses a duration string. such as "300ms", "-1.5h" or "2h45m". Valid time units are "ns", "us" (or "µs"), "ms", "s", "m", "h".

func SetLocalByName

go
func SetLocalByName(tzName string) error

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

func ToDur

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

ToDur parse a duration string. alias of ToDuration()

func ToDuration

go
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

go
func ToLayout(template string) string

ToLayout convert chars date template to Go date layout.

template chars see time_util.charMap

func ToTime

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

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

func TodayEnd

go
func TodayEnd() time.Time

TodayEnd time

func TodayStart

go
func TodayStart() time.Time

TodayStart time

func TryToTime

go
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.

type ParseRangeOpt

ParseRangeOpt is the option for ParseRange

go
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)
}

type Time

Time an enhanced time.Time implementation.

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

func FromDate

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

FromDate create from datetime string.

func FromString

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

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

func FromTime

go
func FromTime(t time.Time) *Time

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

func FromUnix

go
func FromUnix(sec int64) *Time

FromUnix create from unix time

func Local

go
func Local() *Time

Local time for now

func LocalByName

go
func LocalByName(tzName string) *Time

LocalByName time for now

func New

go
func New(t time.Time) *Time

New instance form given time

func Now

go
func Now() *Time

Now time instance

func Wrap

go
func Wrap(t time.Time) *Time

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

func (*Time) AddDay

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

AddDay add some day time for the time

func (*Time) AddDur

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

AddDur some duration time

func (*Time) AddHour

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

AddHour add some hour time

func (*Time) AddMinutes

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

AddMinutes add some minutes time for the time

func (*Time) AddSeconds

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

AddSeconds add some seconds time the time

func (*Time) AddString

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

AddString add duration time string.

Example:

tn := time_util.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

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

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

func (*Time) DateFormat

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

DateFormat use input template format time to date.

Example:

tn := time_util.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

go
func (t *Time) Datetime() string

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

func (*Time) DayAfter

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

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

func (*Time) DayAgo

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

DayAgo get some day ago time for the time

func (*Time) DayEnd

go
func (t *Time) DayEnd() *Time

DayEnd get time at 23:59:59

func (*Time) DayStart

go
func (t *Time) DayStart() *Time

DayStart get time at 00:00:00

func (Time) Diff

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

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

func (Time) DiffSec

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

DiffSec calc diff seconds for t - u

func (Time) DiffUnix

go
func (t Time) DiffUnix(u int64) int

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

func (*Time) Format

go
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

go
func (t *Time) HourEnd() *Time

HourEnd time

func (*Time) HourStart

go
func (t *Time) HourStart() *Time

HourStart time

func (Time) HowLongAgo

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

HowLongAgo format diff time to string.

func (*Time) IsAfter

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

IsAfter the given time

func (*Time) IsAfterUnix

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

IsAfterUnix the given unix timestamp

func (*Time) IsBefore

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

IsBefore the given time

func (*Time) IsBeforeUnix

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

IsBeforeUnix the given unix timestamp

func (*Time) SubDay

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

SubDay add some day time for the time

func (*Time) SubHour

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

SubHour minus some hour time

func (*Time) SubMinutes

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

SubMinutes minus some minutes time for the time

func (*Time) SubSeconds

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

SubSeconds minus some seconds time the time

func (Time) SubUnix

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

SubUnix calc diff seconds for t - u

func (Time) T

go
func (t Time) T() time.Time

T returns the t.Time

func (Time) Timestamp

go
func (t Time) Timestamp() int64

Timestamp value. alias of t.Unix()

func (*Time) Tomorrow

go
func (t *Time) Tomorrow() *Time

Tomorrow time. get tomorrow time for the time

func (*Time) TplFormat

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

TplFormat use input template format time to date.

alias of DateFormat()

func (*Time) UnmarshalJSON

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

UnmarshalJSON implements the json.Unmarshaler interface.

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

func (*Time) UnmarshalText

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

UnmarshalText implements the encoding.TextUnmarshaler interface.

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

func (*Time) Yesterday

go
func (t *Time) Yesterday() *Time

Yesterday get day ago time for the time

type TimeMessage

TimeMessage struct for HowLongAgo2(), FromNowWith()

go
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
}

type TimeX

TimeX alias of Time Deprecated: use Time instead

go
type TimeX = Time

Generated by gomarkdoc