ztime

package
v0.0.0-...-49fafbb Latest Latest
Warning

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

Go to latest
Published: Nov 25, 2024 License: MIT Imports: 9 Imported by: 11

Documentation

Overview

Package ztime implements functions for date and time.

Index

Constants

This section is empty.

Variables

View Source
var DefaultRangeLocale = RangeLocale{
	Months: [12]string{"January", "February", "March", "April", "May",
		"June", "July", "August", "September", "October", "November", "December"},
	MonthsShort: [12]string{"Jan", "Feb", "Mar", "Apr", "May", "Jun",
		"Jul", "Aug", "Sep", "Oct", "Nov", "Dec"},
	Days:      [7]string{"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"},
	DaysShort: [7]string{"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"},

	Today:     func() string { return "Today" },
	Yesterday: func() string { return "Yesterday" },
	Month: func(m time.Month) string {
		return []string{"January", "February", "March", "April", "May", "June",
			"July", "August", "September", "October", "November", "December"}[m-1]
	},
	DayAgo: func(n int) string {
		if n == 1 {
			return "1 day ago"
		}
		return strconv.Itoa(n) + " days ago"
	},
	WeekAgo: func(n int) string {
		if n == 1 {
			return "1 week ago"
		}
		return strconv.Itoa(n) + " weeks ago"
	},
	MonthAgo: func(n int) string {
		if n == 1 {
			return "1 month ago"
		}
		return strconv.Itoa(n) + " months ago"
	},
}
View Source
var Now = func() time.Time { return time.Now().UTC() }

Now returns the current time as UTC.

This can be swapped out in tests with SetNow()

TODO: this shouldn't use .UTC(), at least not by default.

Functions

func AddPeriod

func AddPeriod(t time.Time, n int, p Period) time.Time

AddPeriod adds time period.

This matches common understanding of what things like "next month" mean; adding or subtracting months will always end up in the expected month, regardless of the number of days in either month.

For example:

Jan 31 + 1 month  = Feb 28 (or Feb 29, if it's a leap year)
Dec 31 - 3 months = Sep 30

This is done for Month, Quarter, and HalfYear.

There is one special case for Year: if the date is Feb 29th, adding or subtracting a year will land you on Feb 28th.

Since leap seconds are irregular and unpredictable they are not handled. The entire concept is silly and most programs should just pretend they don't exist.

func DaysInMonth

func DaysInMonth(t time.Time) int

DaysInMonth returns the number of days for this month.

func DurationAs

func DurationAs(d, as time.Duration) string

DurationAs formats a duration as the given time unit, with fractions (if any).

For example DurationAs(d, time.Millisecond) will return "0.05" for 50 microseconds.

Use Round() if you want to limit the precision.

func EndOf

func EndOf(t time.Time, p Period) time.Time

EndOf adjusts the time to the end of the given period.

For example EndOf(t, QuarterHour) with "15:19" will adjust the time to "15:30".

func FromString

func FromString(s string) time.Time

FromString creates a new date from a string according to the layout:

2006-01-02 15:04:05 MST

Any part on the right can be omitted; for example "2020-01-01" will create a new date without any time, or "2020-01-01 13" will create a date with the hour set.

A timezone can always be added, for example "2020-01-01 13 CET".

This will panic on errors. This is mostly useful in tests to quickly create a date without too much ceremony.

func LastInMonth

func LastInMonth(t time.Time) bool

LastInMonth reports if the current day is the last day in this month.

func LeapYear

func LeapYear(t time.Time) bool

LeapYear reports if this year is a leap year according to the Gregorian calendar.

func MustParse

func MustParse(layout, value string) time.Time

MustParse is like time.Parse, but will panic on errors.

func SetNow

func SetNow(t *testing.T, s string)

SetNow sets Now() and restores it when the test finishes.

The date is parsed with FromString().

func Sleep

func Sleep(ctx context.Context, d time.Duration)

Sleep for d duration, or until the context times out.

func StartOf

func StartOf(t time.Time, p Period) time.Time

StartOf adjusts the time to the start of the given period.

For example StartOf(t, QuarterHour) with "15:19" will adjust the time to "15:15".

func Takes

func Takes(f func()) time.Duration

Takes records how long the execution of f takes.

func Unpack

func Unpack(t time.Time) (year int, month time.Month, day, hour, minute, second, nanosecond int, loc *time.Location)

Unpack a time to its individual components.

Types

type Diff

type Diff struct {
	Years, Months, Weeks, Days int
	Hours, Mins, Secs          int
}

Diff represents the difference between two times.

func (Diff) String

func (d Diff) String() string

TODO: i18n this.

type Durations

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

Durations is a list of time.Durations.

This is useful if you want to record a list of durations; for example to keep track of performance metrics.

All operations are thread-safe.

func NewDurations

func NewDurations(max int) Durations

NewDurations creates a new Durations.

The maximum size of the list is set to max items. After this, the oldest entries will be removed. Set to not have an upper limit.

func (*Durations) Append

func (d *Durations) Append(add ...time.Duration)

Append durations to the list.

func (Durations) Distrubute

func (d Durations) Distrubute(n int) []Durations

Distrubute the list of Durations in n blocks.

For example with Distribute(5) it returns 5 set of durations, from the fastest 20% to the slowest 20%.

func (*Durations) Grow

func (d *Durations) Grow(n int)

Grow the list of durations for another n durations.

After Grow(n), at least n items can be appended without another allocation.

Grow will panic if n is negative or if the list can't grow (i.e. larger than MaxInt items).

func (Durations) Len

func (d Durations) Len() int

Len returns the number of durations in this list.

func (Durations) List

func (d Durations) List() []time.Duration

List returns a copy of all durations.

func (Durations) Max

func (d Durations) Max() time.Duration

Max returns the maximum value in this list.

func (Durations) Mean

func (d Durations) Mean() time.Duration

Mean returns the mean average of the durations in this list.

func (Durations) Median

func (d Durations) Median() time.Duration

Median returns the median average of the durations in this list.

func (Durations) Min

func (d Durations) Min() time.Duration

Min returns the minimum value in this list.

func (Durations) String

func (d Durations) String() string

func (Durations) Sum

func (d Durations) Sum() time.Duration

Sum returns the sum of all durations in this list.

func (Durations) Top

func (d Durations) Top(percent int) Durations

Top gets the top percent items in this list.

e.g. with a list of 200 durations, Top(10) returns the top 10% longest durations (20 of them). Use negative numbers to get the bottom percentile (the fastest 10%).

The return value is a copy.

Numbers higher than 100 or lower than -100 will panic.

type Period

type Period uint8

Period to adjust or align a time by.

const (
	Second Period
	Minute
	QuarterHour
	HalfHour
	Hour
	Day
	WeekMonday
	WeekSunday
	Month
	Quarter
	HalfYear
	Year
)

Periods to adjust or align a time by.

func Week

func Week(sundayStartsWeek bool) Period

Week returns WeekSunday or WeekMonday.

func (Period) String

func (p Period) String() string

type Range

type Range struct {
	Start time.Time `json:"start"`
	End   time.Time `json:"end"`
	// contains filtered or unexported fields
}

A Range represents a time range from Start to End.

The timezone is always taken from the start time. The end's timezone will be adjusted if it differs.

func NewRange

func NewRange(start time.Time) Range

NewRange creates a new range with the start date set.

func (Range) Current

func (r Range) Current(p Period) Range

Current returns a copy with the start and end times set the current Period p.

This uses the value of the start time. Any value in the end time is ignored.

For example with NewRange("2020-06-18 14:00:00"):

Current(Month)       2020-06-01 00:00:00       → 2020-06-30 23:59:59
Current(WeekMonday)  2020-06-15 00:00:00 (Mon) → 2020-06-21 23:59:59 (Sun)

func (Range) Diff

func (r Range) Diff(periods ...Period) Diff

Diff gets the difference between two dates.

Optionally pass any Period arguments to get the difference in those periods, ignoring any others. For example "Month, Day" would return "29 months, 6 days", instead of "2 years, 5 months, 6 days". The default is to get everything excluding weeks.

Adapted from https://stackoverflow.com/a/36531443/660921

func (Range) Equal

func (r Range) Equal(cmp Range) bool

Equal reports whether this range equals the given time range with time.Time.Equal().

func (Range) From

func (r Range) From(start time.Time) Range

From returns a copy with the start time set.

This will apply the timezone from the passed start time to the end time.

func (Range) In

func (r Range) In(loc *time.Location) Range

In returns a copy with the timezone set to loc.

func (Range) IsZero

func (r Range) IsZero() bool

IsZero reports whether both the start and end date represent the zero time instant with time.Time.Equal().

func (Range) Last

func (r Range) Last(p Period) Range

Last returns a copy with the start and end times set to the last Period p.

This uses the value of the start time. Any value in the end time is ignored.

For example with NewRange("2020-06-18 14:00:00") (Thursday):

Last(Month)       2020-05-18 00:00:00       → 2020-06-18 23:59:59
Last(WeekMonday)  2020-06-11 00:00:00 (Wed) → 2020-06-18 23:59:59 (Thu)

func (Range) Locale

func (r Range) Locale(l RangeLocale) Range

Locale sets the translated strings to use for this time range.

Any of the struct values will default to DefaultRangeLocale if one of the struct values isn't set, so this:

rng = rng.Locale(RangeLocale{Today: func() string { return ".." }})

Will work.

func (Range) Period

func (r Range) Period(n int, p Period) Range

Period returns a copy withh the end time set to n Period from the start time.

This uses ztime.AddPeriod() and its "common sense" understanding of months.

func (Range) Round

func (r Range) Round(d time.Duration) Range

Round returns the result of rounding the start and end dates to the nearest multiple of the given duration with time.Time.Round().

func (Range) String

func (r Range) String() string

String shows the range from start to end as a human-readable representation; e.g. "current week", "last week", "previous month", etc.

It falls back to "Mon Jan 2–Mon Jan 2" if there's no clear way to describe it.

TODO: i18n for months names; should really use CLDR for "short" format too.

func (Range) To

func (r Range) To(end time.Time) Range

To returns a copy with the end time set.

This will apply the timezone from the start time to the passed end time.

func (Range) Truncate

func (r Range) Truncate(d time.Duration) Range

Truncate returns the result of rounding the start and end dates down to a multiple of the given duration with time.Time.Truncate().

func (Range) UTC

func (r Range) UTC() Range

In returns a copy with the timezone set to UTC.

type RangeLocale

type RangeLocale struct {
	Months      [12]string
	MonthsShort [12]string
	Days        [7]string
	DaysShort   [7]string
	Today       func() string             // "Today"
	Yesterday   func() string             // "Yesterday"
	Month       func(m time.Month) string // "January", "December"
	DayAgo      func(n int) string        // "1 day ago", "5 days ago"
	WeekAgo     func(n int) string        // "1 week ago", "5 weeks ago"
	MonthAgo    func(n int) string        // "1 month ago", "5 months ago"
}

RangeLocale can be used to translate the output of Range.String().

This defaults to DefaultRangeLocale.

type Time

type Time struct{ time.Time }

Time wraps time.Time to add {Start,End}Of, AddPeriod(), and Unpack(). It also wraps operations that return time.Time to return ztime.Time.

func (Time) Add

func (t Time) Add(d time.Duration) Time

func (Time) AddDate

func (t Time) AddDate(years, months, days int) Time

func (Time) AddPeriod

func (t Time) AddPeriod(n int, p Period) Time

func (Time) EndOf

func (t Time) EndOf(p Period) Time

func (Time) In

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

func (Time) Local

func (t Time) Local() Time

func (Time) Round

func (t Time) Round(d time.Duration) Time

func (Time) StartOf

func (t Time) StartOf(p Period) Time

func (Time) Truncate

func (t Time) Truncate(d time.Duration) Time

func (Time) UTC

func (t Time) UTC() Time

func (Time) Unpack

func (t Time) Unpack() (year int, month time.Month, day, hour, minute, second, nanosecond int, loc *time.Location)

Jump to

Keyboard shortcuts

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