timeutil

package module
v0.2.0 Latest Latest
Warning

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

Go to latest
Published: Aug 15, 2026 License: MIT Imports: 3 Imported by: 0

Documentation

Overview

Package timeutil provides time utilities:

  • Formatting & parsing with timezone support
  • Time ranges (start/end of day, week, month, year)
  • Timers (stopwatch, countdown, debounce)
  • Common duration helpers
  • Business-day calculations

Quick start

// Format with timezone
timeutil.FormatIn(time.Now(), "2006-01-02 15:04:05", "Asia/Shanghai")

// Parse with timezone
t, err := timeutil.ParseIn("2026-08-15 10:00:00", "2006-01-02 15:04:05", "Asia/Shanghai")

// Start of day in local timezone
start := timeutil.StartOfDay(time.Now())

// Stopwatch
sw := timeutil.NewStopwatch()
sw.Start()
// ... do work ...
elapsed := sw.Elapsed()

Index

Constants

View Source
const (
	LayoutDate      = "2006-01-02"
	LayoutDateTime  = "2006-01-02 15:04:05"
	LayoutTime      = "15:04:05"
	LayoutISO8601   = "2006-01-02T15:04:05Z07:00"
	LayoutRFC3339   = time.RFC3339
	LayoutRFC822    = "02 Jan 06 15:04 MST"
	LayoutRFC1123   = "Mon, 02 Jan 2006 15:04:05 MST"
	LayoutUnix      = "2006-01-02 15:04:05 -0700 MST"
	LayoutTimestamp = "20060102150405"
	LayoutSlash     = "2006/01/02 15:04:05"
	LayoutCNDate    = "2006年01月02日"
	LayoutCNTime    = "2006年01月02日 15时04分05秒"
)

Common time formats.

View Source
const (
	Nanosecond  = time.Nanosecond
	Microsecond = time.Microsecond
	Millisecond = time.Millisecond
	Second      = time.Second
	Minute      = time.Minute
	Hour        = time.Hour
	Day         = 24 * time.Hour
	Week        = 7 * 24 * time.Hour
)

Common durations for convenience.

Variables

This section is empty.

Functions

func AddBusinessDays

func AddBusinessDays(t time.Time, n int) time.Time

AddBusinessDays adds n business days (Mon-Fri) to the given time, preserving the time-of-day. Negative n subtracts business days.

func AddDuration

func AddDuration(d time.Duration) int64

AddDuration returns the Unix timestamp after adding d to now.

func Age

func Age(t time.Time) time.Duration

Age returns the duration between the given time and now.

func BusinessDaysBetween

func BusinessDaysBetween(start, end time.Time) int

BusinessDaysBetween returns the number of business days between two times (exclusive of both endpoints). Returns 0 if start >= end.

func CalculateAge

func CalculateAge(birthday time.Time) int

CalculateAge returns the age in years given a birthday.

func Clamp

func Clamp(t, start, end time.Time) time.Time

Clamp ensures a time is within a range. If t is before start, returns start. If t is after end, returns end. Otherwise returns t.

func DaysInMonth

func DaysInMonth(t time.Time) int

DaysInMonth returns the number of days in the month of the given time.

func Debounce

func Debounce(wait time.Duration, fn func()) func()

Debounce creates a debounced function that delays invoking fn until after wait duration has elapsed since the last time it was invoked. The returned function is safe for concurrent use.

func DurationToHuman

func DurationToHuman(d time.Duration) string

DurationToHuman returns a human-readable duration string. e.g. "2h30m", "1d4h", "30s", "500ms".

func EndOfDay

func EndOfDay(t time.Time) time.Time

EndOfDay returns the end of the day (23:59:59.999999999) for the given time.

func EndOfHour

func EndOfHour(t time.Time) time.Time

EndOfHour returns the end of the hour for the given time.

func EndOfMinute

func EndOfMinute(t time.Time) time.Time

EndOfMinute returns the end of the minute for the given time.

func EndOfMonth

func EndOfMonth(t time.Time) time.Time

EndOfMonth returns the end of the month (last day 23:59:59.999999999).

func EndOfWeek

func EndOfWeek(t time.Time) time.Time

EndOfWeek returns the end of the week (Sunday 23:59:59.999999999).

func EndOfYear

func EndOfYear(t time.Time) time.Time

EndOfYear returns December 31st 23:59:59.999999999 of the given time's year.

func Format

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

Format formats a time using the given layout in the local timezone.

func FormatDate

func FormatDate(t time.Time) string

FormatDate returns the date part as "2006-01-02".

func FormatDateTime

func FormatDateTime(t time.Time) string

FormatDateTime returns the time as "2006-01-02 15:04:05".

func FormatIn

func FormatIn(t time.Time, layout, locName string) string

FormatIn formats a time using the given layout in the specified timezone.

func FormatTimestamp

func FormatTimestamp(t time.Time) string

FormatTimestamp returns the time as a Unix-style timestamp string (e.g. "20260815100000").

func FormatUTC

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

FormatUTC formats a time using the given layout in UTC.

func FromMicros

func FromMicros(us int64) time.Time

FromMicros converts a Unix timestamp (microseconds) to time.Time.

func FromMillis

func FromMillis(ms int64) time.Time

FromMillis converts a Unix timestamp (milliseconds) to time.Time.

func FromUnix

func FromUnix(sec int64) time.Time

FromUnix converts a Unix timestamp (seconds) to time.Time.

func In

func In(t time.Time, loc *time.Location) time.Time

In converts a time to the given timezone.

func InLocation

func InLocation(t time.Time, name string) (time.Time, error)

InLocation converts a time to the named timezone.

func IsBusinessDay

func IsBusinessDay(t time.Time) bool

IsBusinessDay returns true if the given time is a weekday (Mon-Fri).

func IsExpired

func IsExpired(t time.Time) bool

IsExpired returns true if the given time is before now.

func IsLeapYear

func IsLeapYear(t time.Time) bool

IsLeapYear returns true if the year of the given time is a leap year.

func IsWeekend

func IsWeekend(t time.Time) bool

IsWeekend returns true if the given time is a weekend (Sat or Sun).

func IsZero

func IsZero(t time.Time) bool

IsZero returns true if the given time is the zero value.

func Location

func Location(name string) (*time.Location, error)

Location returns the *time.Location for the given name. Returns time.Local if name is empty or "Local". Returns time.UTC if name is "UTC". Returns an error for unknown timezone names.

func Max

func Max(a, b time.Time) time.Time

Max returns the later of two times.

func MicrosNow

func MicrosNow() int64

MicrosNow returns the current Unix timestamp in microseconds.

func MillisNow

func MillisNow() int64

MillisNow returns the current Unix timestamp in milliseconds.

func Min

func Min(a, b time.Time) time.Time

Min returns the earlier of two times.

func MustInLocation

func MustInLocation(t time.Time, name string) time.Time

MustInLocation converts a time to the named timezone, panicking on error.

func MustLocation

func MustLocation(name string) *time.Location

MustLocation is like Location but panics on error.

func MustParse

func MustParse(value, layout string) time.Time

MustParse parses a time string, panicking on error.

func NextBusinessDay

func NextBusinessDay(t time.Time) time.Time

NextBusinessDay returns the next business day after the given time.

func Now

func Now() time.Time

Now returns the current local time.

func NowUTC

func NowUTC() time.Time

NowUTC returns the current UTC time.

func Parse

func Parse(value, layout string) (time.Time, error)

Parse parses a time string using the given layout in the local timezone.

func ParseDuration

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

ParseDuration parses a duration string. Supports standard Go duration syntax (e.g. "1h30m", "500ms") and additional units:

  • "d" for days (e.g. "3d" = 72h)
  • "w" for weeks (e.g. "2w" = 336h)

func ParseIn

func ParseIn(value, layout, locName string) (time.Time, error)

ParseIn parses a time string using the given layout in the specified timezone. The parsed time is adjusted to the given location.

func ParseLocal

func ParseLocal(value, layout string) (time.Time, error)

ParseLocal parses a time string using the given layout in the local timezone.

func ParseUTC

func ParseUTC(value, layout string) (time.Time, error)

ParseUTC parses a time string using the given layout in UTC.

func PreviousBusinessDay

func PreviousBusinessDay(t time.Time) time.Time

PreviousBusinessDay returns the previous business day before the given time.

func StartOfDay

func StartOfDay(t time.Time) time.Time

StartOfDay returns the start of the day (00:00:00) for the given time.

func StartOfHour

func StartOfHour(t time.Time) time.Time

StartOfHour returns the start of the hour for the given time.

func StartOfMinute

func StartOfMinute(t time.Time) time.Time

StartOfMinute returns the start of the minute for the given time.

func StartOfMonth

func StartOfMonth(t time.Time) time.Time

StartOfMonth returns the start of the month (1st day 00:00:00).

func StartOfWeek

func StartOfWeek(t time.Time) time.Time

StartOfWeek returns the start of the week (Monday 00:00:00) for the given time.

func StartOfYear

func StartOfYear(t time.Time) time.Time

StartOfYear returns January 1st 00:00:00 of the given time's year.

func UnixNow

func UnixNow() int64

UnixNow returns the current Unix timestamp in seconds.

func Yesterday

func Yesterday() time.Time

Yesterday returns the time 24 hours ago.

Types

type Countdown

type Countdown struct {
	// contains filtered or unexported fields
}

Countdown is a countdown timer that calls a function when the countdown reaches zero. It is not reusable; create a new one for each countdown.

func NewCountdown

func NewCountdown(dur time.Duration, fn func()) *Countdown

NewCountdown creates a countdown timer that fires fn after dur. The timer starts immediately.

func (*Countdown) Done

func (c *Countdown) Done() <-chan struct{}

Done returns a channel that is closed when the countdown fires.

func (*Countdown) Remaining

func (c *Countdown) Remaining() time.Duration

Remaining returns the time remaining until the countdown fires. Returns 0 if the countdown has fired or been stopped.

func (*Countdown) Stop

func (c *Countdown) Stop() bool

Stop cancels the countdown. Returns true if the countdown was successfully stopped (i.e., it hadn't fired yet).

type Stopwatch

type Stopwatch struct {
	// contains filtered or unexported fields
}

Stopwatch is a simple stopwatch that can be started, stopped, and reset. It is safe for concurrent use.

func NewStopwatch

func NewStopwatch() *Stopwatch

NewStopwatch creates a new stopwatch. The stopwatch is not running.

func (*Stopwatch) Elapsed

func (s *Stopwatch) Elapsed() time.Duration

Elapsed returns the total elapsed time, including the current running period if the stopwatch is running.

func (*Stopwatch) IsRunning

func (s *Stopwatch) IsRunning() bool

IsRunning returns true if the stopwatch is currently running.

func (*Stopwatch) Lap

func (s *Stopwatch) Lap() time.Duration

Lap records a lap time and returns the duration since the last lap (or since Start if this is the first lap).

func (*Stopwatch) Laps

func (s *Stopwatch) Laps() []time.Duration

Laps returns all recorded lap times.

func (*Stopwatch) Reset

func (s *Stopwatch) Reset()

Reset resets the stopwatch, clearing all elapsed time and laps.

func (*Stopwatch) Start

func (s *Stopwatch) Start()

Start begins timing. If already running, it is a no-op.

func (*Stopwatch) Stop

func (s *Stopwatch) Stop() time.Duration

Stop stops timing and returns the total elapsed duration. If not running, it returns the accumulated elapsed time.

type TimeRange

type TimeRange struct {
	Start, End time.Time
}

TimeRange represents a half-open time range [Start, End).

func NewTimeRange

func NewTimeRange(start, end time.Time) TimeRange

NewTimeRange creates a TimeRange from start and end times.

func ThisMonthRange

func ThisMonthRange() TimeRange

ThisMonthRange returns the time range for the current month.

func ThisWeekRange

func ThisWeekRange() TimeRange

ThisWeekRange returns the time range for the current week.

func ThisYearRange

func ThisYearRange() TimeRange

ThisYearRange returns the time range for the current year.

func TodayRange

func TodayRange() TimeRange

TodayRange returns the time range for today [StartOfDay, EndOfDay].

func YesterdayRange

func YesterdayRange() TimeRange

YesterdayRange returns the time range for yesterday.

func (TimeRange) Contains

func (r TimeRange) Contains(t time.Time) bool

Contains returns true if the range contains the given time.

func (TimeRange) ContainsInclusive

func (r TimeRange) ContainsInclusive(t time.Time) bool

ContainsInclusive returns true if the range contains the given time, inclusive of the end boundary.

func (TimeRange) Duration

func (r TimeRange) Duration() time.Duration

Duration returns the duration of the range.

func (TimeRange) Intersect

func (r TimeRange) Intersect(other TimeRange) (TimeRange, bool)

Intersect returns the intersection of two ranges, or ok=false if they don't overlap.

func (TimeRange) Overlaps

func (r TimeRange) Overlaps(other TimeRange) bool

Overlaps returns true if this range overlaps with another.

func (TimeRange) Split

func (r TimeRange) Split(n int) []TimeRange

Split splits the range into n equal sub-ranges. Panics if n <= 0.

Jump to

Keyboard shortcuts

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