timekit

package module
v0.0.0-...-cad2325 Latest Latest
Warning

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

Go to latest
Published: Jan 30, 2024 License: ISC Imports: 5 Imported by: 94

README

timekit

GoDoc Go Report Card License Go version

Convenience functions to make your life easier when using with Golang's time package.

Installation

In your Golang project, please run:

go get github.com/bartmika/timekit

Documentation

All documentation can be found here.

Example Usage

The following usage section will show a few interesting solutions that can be solved by this library.

How do I get the first day of this year in Golang?
import (
    "fmt"

    "github.com/bartmika/timekit"
)

startOfYearDate := timekit.FirstDayOfThisYear(time.Now)
fmt.Println(startOfYearDate)

If you have interest in finding out more functions for getting different date/times then checkout timekit.go file.

How do parse JavaScript time into Golang time?

In your browser console, try writing this:

// EXAMPLE JAVASCRIPT CODE
var dt = new Date()
console.log(dt.getTime()) // 1643082322380
console.log(dt) // Mon Jan 24 2022 22:45:22 GMT-0500 (Eastern Standard Time)

Then try this in your go source file:

import (
    "fmt"

    "github.com/bartmika/timekit"
)

jsTime := int64(1643082322380)
goTime := ParseJavaScriptTime(jsTime)
fmt.Println(goTime)
How get a range of date/times between two dates?
import (
    "fmt"

    "github.com/bartmika/timekit"
)

start := time.Date(2022, 1, 7, 1, 0, 0, 0, loc) // Jan 7th 2022
end := time.Date(2022, 1, 10, 1, 0, 0, 0, loc)  // Jan 10th 2022
dts := RangeFromTimeStepper(start, end, 0, 0, 1, 0, 0, 0) // Step by day.
fmt.Println(dts) // Output:
                 // Jan 7th 2022
                 // Jan 8th 2022
                 // Jan 9th 2022
                 // Jan 10th 2022

If you have interest in finding out more range functions then checkout range.go and timestepper.go files.

How get iterate between two dates?
import (
    "fmt"

    "github.com/bartmika/timekit"
)

loc := time.UTC                                 // closure can be used if necessary
start := time.Date(2022, 1, 7, 1, 0, 0, 0, loc) // Jan 7th 2022
end := time.Date(2022, 1, 10, 1, 0, 0, 0, loc)  // Jan 10th 2022
ts := NewTimeStepper(start, end, 0, 0, 1, 0, 0, 0)

var actual time.Time
running := true
for running {
    // Get the value we are on in the timestepper.
    actual = ts.Get()

    log.Println(actual) // For debugging purposes only.

    // Run our timestepper to get our next value.
    ts.Next()

    running = ts.Done() == false
}

If you have interest in finding out iterating between two date/times then checkout timestepper.go file.

Contributing

Found a bug? Want a feature to improve your developer experience when dealing with the time package? Please create an issue.

License

Made with ❤️ by Bartlomiej Mika.
The project is licensed under the ISC License.

Resource used:

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func AddWeeksToTime

func AddWeeksToTime(dt time.Time, weeks int) time.Time

AddWeeksToTime returns new time with weeks added to it.

func DaysRange

func DaysRange(start time.Time, end time.Time) []int

DaysRange returns an array of the day integer values between two dates. For example if one date is January 1st 2000 and the other is January 5th 2000, the output will be [1,2,3,4,5].

func EqualWithDrift

func EqualWithDrift(t1 time.Time, t2 time.Time, drift time.Duration) bool

EqualWithDrift function will compare two date/times but will allow duration margin of error (which we call drift) between the comparison. For example, if we have +/- 2 second margin of error (aka drift) and input 2022-12-20T08:36:38Z and 2022-12-20T08:36:39Z then the result should be equal.

func FirstDayOfLastISOWeek

func FirstDayOfLastISOWeek(now func() time.Time) time.Time

FirstDayOfLastISOWeek returns the previous week's monday date.

func FirstDayOfLastMonth

func FirstDayOfLastMonth(now func() time.Time) time.Time

FirstDayOfLastMonth returns the date (with 0:00 hour) of the first day from last month.

func FirstDayOfLastYear

func FirstDayOfLastYear(now func() time.Time) time.Time

FirstDayOfLastYear returns first date (with 0:00 hour) from last calendar year.

func FirstDayOfNextISOWeek

func FirstDayOfNextISOWeek(now func() time.Time) time.Time

FirstDayOfNextISOWeek return date of the upcoming monday.

func FirstDayOfNextMonth

func FirstDayOfNextMonth(now func() time.Time) time.Time

FirstDayOfNextMonth returns next months first day (in 12 AM hours).

func FirstDayOfNextYear

func FirstDayOfNextYear(now func() time.Time) time.Time

FirstDayOfNextYear returns date (12AM) of the first date of next calendar year.

func FirstDayOfThisISOWeek

func FirstDayOfThisISOWeek(now func() time.Time) time.Time

FirstDayOfThisISOWeek return monday's date of this week. Please note monday is considered the first day of the week according to ISO 8601 and not sunday (which is what is used in Canada and USA).

func FirstDayOfThisMonth

func FirstDayOfThisMonth(now func() time.Time) time.Time

FirstDayOfThisMonth returns the first date (with 0:00 hour) from this month.

func FirstDayOfThisYear

func FirstDayOfThisYear(now func() time.Time) time.Time

FirstDayOfThisYear returns the date (with 0:00 hour) from the first date of this calendar year.

func GetDatesByWeeklyBasedRecurringSchedule

func GetDatesByWeeklyBasedRecurringSchedule(startDT time.Time, weekdays []int8, totalWeeks int, weekFrequency int) []time.Time

GetDatesByWeeklyBasedRecurringSchedule Generates a list of datetimes based on a weekly recuring schedule. Please note that dates start in first week and then week frequency is applied to restrict some weeks.

func GetDatesForExactDayByMonthlyBasedRecurringSchedule

func GetDatesForExactDayByMonthlyBasedRecurringSchedule(startDT time.Time, totalMonths int, onExactDay int) []time.Time

GetDatesForExactDayByMonthlyBasedRecurringSchedule Generates a list of datetimes based on a monthly recuring schedule for the specific day number.

func GetDatesForFirstWeekDayByMonthlyBasedRecurringSchedule

func GetDatesForFirstWeekDayByMonthlyBasedRecurringSchedule(startDT time.Time, totalMonths int, onFirstWeekday int) []time.Time

GetDatesForFirstWeekDayByMonthlyBasedRecurringSchedule Generates a list of datetimes based on a monthly recuring schedule which will find all the dates that fall on the weekday of the first week.

func GetDatesForLastWeekDayByMonthlyBasedRecurringSchedule

func GetDatesForLastWeekDayByMonthlyBasedRecurringSchedule(startDT time.Time, totalMonths int, onLastWeekday int) []time.Time

GetDatesForLastWeekDayByMonthlyBasedRecurringSchedule Generates a list of datetimes based on a monthly recuring schedule which will find all the dates that fall on the weekday of the last week.

func GetDatesForWeekdaysBetweenRange

func GetDatesForWeekdaysBetweenRange(start time.Time, end time.Time, weekdays []int8) []time.Time

GetDatesForWeekdaysBetweenRange returns all the date-times between two dates that fall for the specific picked weekdays.

func GetDayOfWeekUsingTomohikoSakamotoAlgorithm

func GetDayOfWeekUsingTomohikoSakamotoAlgorithm(d uint64, m uint64, y uint64) uint64

GetDayOfWeekUsingTomohikoSakamotoAlgorithm returns the day of the week where `0` = Sunday, `1` = Monday, etc.

func GetFirstDateFromMonthAndYear

func GetFirstDateFromMonthAndYear(month int, year int, loc *time.Location) time.Time

GetFirstDateFromMonthAndYear returns the first day in the month/year specified.

func GetFirstDateFromWeekAndYear

func GetFirstDateFromWeekAndYear(wk int, year int, loc *time.Location) time.Time

GetFirstDateFromWeekAndYear returns the first date for the particular week in the year inputted.

func GetFutureDateByFiveMinuteIntervalPattern

func GetFutureDateByFiveMinuteIntervalPattern(dt time.Time) time.Time

GetFutureDateByFiveMinuteIntervalPattern returns the future date that conforms to the 5 minute interval pattern. For example: Sunday Jan 9th - 1:00 AM --> Sunday Jan 9th - 1:00 AM Sunday Jan 9th - 1:01 AM --> Sunday Jan 9th - 1:05 AM Sunday Jan 9th - 1:28 AM --> Sunday Jan 9th - 1:30 AM Sunday Jan 9th - 1:59 AM --> Sunday Jan 9th - 2:00 AM Sunday Jan 9th - 11:59 PM --> Sunday Jan 10th - 12:00 AM

func GetFutureDateByFiveteenMinuteIntervalPattern

func GetFutureDateByFiveteenMinuteIntervalPattern(dt time.Time) time.Time

GetFutureDateByFiveteenMinuteIntervalPattern returns the future date that conforms to the 5 minute interval pattern. For example: Sunday Jan 9th - 1:00 AM --> Sunday Jan 9th - 1:00 AM Sunday Jan 9th - 1:01 AM --> Sunday Jan 9th - 1:15 AM Sunday Jan 9th - 1:28 AM --> Sunday Jan 9th - 1:30 AM Sunday Jan 9th - 1:59 AM --> Sunday Jan 9th - 2:00 AM Sunday Jan 9th - 11:59 PM --> Sunday Jan 10th - 12:00 AM

func GetFutureDateByOneHourIntervalPattern

func GetFutureDateByOneHourIntervalPattern(dt time.Time) time.Time

GetFutureDateByOneHourIntervalPattern returns the future date that conforms to the 5 minute interval pattern. For example: Sunday Jan 9th - 1:00 AM --> Sunday Jan 9th - 1:00 AM Sunday Jan 9th - 1:01 AM --> Sunday Jan 9th - 1:05 AM Sunday Jan 9th - 1:28 AM --> Sunday Jan 9th - 1:30 AM Sunday Jan 9th - 1:59 AM --> Sunday Jan 9th - 2:00 AM Sunday Jan 9th - 11:59 PM --> Sunday Jan 10th - 12:00 AM

func GetFutureDateByTenMinuteIntervalPattern

func GetFutureDateByTenMinuteIntervalPattern(dt time.Time) time.Time

GetFutureDateByTenMinuteIntervalPattern returns the future date that conforms to the 5 minute interval pattern. For example: Sunday Jan 9th - 1:00 AM --> Sunday Jan 9th - 1:00 AM Sunday Jan 9th - 1:01 AM --> Sunday Jan 9th - 1:10 AM Sunday Jan 9th - 1:28 AM --> Sunday Jan 9th - 1:30 AM Sunday Jan 9th - 1:59 AM --> Sunday Jan 9th - 2:00 AM Sunday Jan 9th - 11:59 PM --> Sunday Jan 10th - 12:00 AM

func GetFutureDateByThirtyMinuteIntervalPattern

func GetFutureDateByThirtyMinuteIntervalPattern(dt time.Time) time.Time

GetFutureDateByThirtyMinuteIntervalPattern returns the future date that conforms to the 5 minute interval pattern. For example: Sunday Jan 9th - 1:00 AM --> Sunday Jan 9th - 1:00 AM Sunday Jan 9th - 1:01 AM --> Sunday Jan 9th - 1:30 AM Sunday Jan 9th - 1:28 AM --> Sunday Jan 9th - 1:30 AM Sunday Jan 9th - 1:59 AM --> Sunday Jan 9th - 2:00 AM Sunday Jan 9th - 11:59 PM --> Sunday Jan 10th - 12:00 AM

func GetHourRange

func GetHourRange(dt time.Time) (time.Time, time.Time)

GetHourRange function will take a date value and return two date times: (1) The first date time will take the date and discard the minutes, so for example if you give 12:30 PM then it will return 12:00 PM. (2) The second date time will disacrd the minutes and increase by 1 hour, for example if you give 12:30 PM then it will return 1:00 PM. Therefore the purpose of this function is to provide an hourly range for the inputted parameter. For example if I say 12:300 PM then this function will return 12:00 PM & 1:00 AM.

Developers Note: This would be useful to you if are building analytics engine which must group certain miunute based datapoints / timeseries into hours.

Here are some more examples to help you visualize: Monday Dec 18th - 9:30 AM --> (1) Monday Dec 18th - 9:00 AM and (2) Monday Dec 18th - 10:00 AM Monday Dec 18th - 5:10 PM --> (1) Monday Dec 18th - 5:00 PM and (2) Monday Dec 18th - 7:00 PM Monday Dec 18th - 10:55 PM --> (1) Monday Dec 18th - 10:00 PM and (2) Monday Dec 18th - 11:00 PM

func GetMonthAbbreviation

func GetMonthAbbreviation(month time.Month) string

GetMonthAbbreviation returns the 3-character abbreviation for the provided month.

func GetMonthAbbreviationByInt

func GetMonthAbbreviationByInt(month int) string

GetMonthAbbreviationByInt returns the 3-character abbreviation for the provided month number.

func GetWeekNumberFromDate

func GetWeekNumberFromDate(dt time.Time) int

GetWeekNumberFromDate will return the week number for the inputted date.

func GetWeekNumberFromTotalDaysCount

func GetWeekNumberFromTotalDaysCount(daysCount uint64) uint64

GetWeekNumberFromTotalDaysCount returns the week number from total days count. For example daysCount=8, returns=2 or daysCount=365, returned=52.

func HourRangeForNow

func HourRangeForNow(now func() time.Time) (time.Time, time.Time)

HourRangeForNow works just like the `GetHourRange` function however it works for the current date/time.

func IsAfter6PM

func IsAfter6PM(t time.Time) bool

IsAfter6PM returns true if time is after 6PM.

func IsAfternoon

func IsAfternoon(t time.Time) bool

IsAfternoon returns true if time is between 12PM to 4:59PM or (24 to 16:59) in 24 hour format

func IsEvening

func IsEvening(t time.Time) bool

IsEvening returns true if time is between 5PM to 7:59PM or (17 to 19:59) in 24 hour format

func IsFirstDayOfYear

func IsFirstDayOfYear(dt time.Time) bool

IsFirstDayOfYear returns true or false depending on whether the date inputted falls on the very first day of the year.

func IsMorning

func IsMorning(t time.Time) bool

IsMorning returns true if time is between 12 AM to 11:59 AM or (12 to 11:59) in 24 hour format

func IsNight

func IsNight(t time.Time) bool

IsNight returns true if time is between 8PM to 11:59 PM or (20 to 22:59) in 24 hour format

func IsTimeOnFirstWeekOfMonth

func IsTimeOnFirstWeekOfMonth(pickedDT time.Time) bool

func IsTimeOnLastWeekOfMonth

func IsTimeOnLastWeekOfMonth(pickedDT time.Time) bool

func LastDayOfThisISOWeek

func LastDayOfThisISOWeek(now func() time.Time) time.Time

LastDayOfThisISOWeek return sunday's date of this week. Please note sunday is considered the last day of the week according to ISO 8601.

func Midnight

func Midnight(now func() time.Time) time.Time

Midnight return today's date at 12 o’clock (or 0:00) during the night.

func MidnightTomorrow

func MidnightTomorrow(now func() time.Time) time.Time

MidnightTomorrow will return tomorrows date at 12 o’clock (or 0:00) during the night.

func MidnightYesterday

func MidnightYesterday(now func() time.Time) time.Time

MidnightYesterday return 12 AM date of yesterday.

func MonthRange

func MonthRange(start time.Time, end time.Time) []int

MonthRange returns an array of the month integer values between two dates. For example if one date is January 2000 and the other is March 2000, the output will be [1,2,3].

func Noon

func Noon(now func() time.Time) time.Time

Noon will return today's date at 12 o'clock (or 12:00) during the day.

func ParseBubbleTime

func ParseBubbleTime(s string) (time.Time, error)

ParseBubbleTime will convert the date/time string (ex: "Nov 11, 2011 11:00 am") used "https://bubble.io" into Golang `time`. You will find need of this function if the Bubble.io app you built will be making an API call to your Golang backend server.

func ParseHourMinuteSecondDurationString

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

ParseHourMinuteSecondDurationString will convert a HH:MM:SS string (example: "08:30:00") into duration.

func ParseISO8601String

func ParseISO8601String(s string) (time.Time, error)

ParseISO8601String converts ISO8601 compliant date-time string into a Golang `time.Time` object.

func ParseJavaScriptTime

func ParseJavaScriptTime(i int64) time.Time

ParseJavaScriptTime will convert the number of milliseconds since the Unix Epoch parameter into Golang `time` format. As a result, the output of the JavaScript `getTime()` function can be used as the parameter in this function.

func ParseJavaScriptTimeString

func ParseJavaScriptTimeString(s string) (time.Time, error)

ParseJavaScriptTimeString will convert the string of milliseconds integers since the Unix Epoch parameter into Golang `time` format. As a result, the output of the JavaScript `getTime()` function can be used as the parameter in this function.

func RandomDate

func RandomDate(startDate time.Time, endDate time.Time) time.Time

RandomDate Generates a random date between two given dates.

func RangeFromTimeStepper

func RangeFromTimeStepper(start time.Time, end time.Time, yearStep int, monthStep int, dayStep int, hourStep int, minuteStep int, secondStep int) []time.Time

RangeFromTimeStepper function returns an array of datetime values from the starting date up to and including the finish date according to the step pattern specified in the parameter.

func To1AM

func To1AM(t time.Time) time.Time

To1AM will take entered date/time and return same date but time starts at 1 AM (01:00:00).

func ToAmericanDateString

func ToAmericanDateString(t time.Time) string

ToAmericanDateString will convert the Golang Date/Time format into the American style of notation string as mentioned via https://en.wikipedia.org/wiki/Date_and_time_notation_in_the_United_States.

func ToAmericanDateTimeString

func ToAmericanDateTimeString(t time.Time) string

ToAmericanDateTimeString will convert the Golang Date/Time format into the American style of notation string as mentioned via https://en.wikipedia.org/wiki/Date_and_time_notation_in_the_United_States.

func ToISO8601String

func ToISO8601String(t time.Time) string

ToISO8601String will convert the Golang `Date` format into an ISO 8601 formatted date/time string.

func ToJavaScriptTime

func ToJavaScriptTime(t time.Time) int64

ToJavaScriptTime will return a Unix Epoch time value that your JavaScript code can read into JavaScript `Date` format. Example JavaScript code snippet of using the results of this function: `var date = new Date(UNIX_Timestamp * 1000);` as an example.

func WeeksRange

func WeeksRange(start time.Time, end time.Time) []int

WeeksRange returns an array of the week integer values between two dates. For example if one date is January 1st 2022 and the other is January 10th 2022, the output will be [52,1,2].

func YearsRange

func YearsRange(start time.Time, end time.Time) []int

YearsRange returns an array of the year integer values between two dates. For example if one date is 2000 and the other is 2002, the output will be [2000,2001,2002].

Types

type DateInterval

type DateInterval struct {
	Start  time.Time
	Finish time.Time
}

DateInterval struct represents start and end dates.

func RandomDateIntervals

func RandomDateIntervals(startDate time.Time, endDate time.Time, maxSeconds int64) []*DateInterval

RandomDateIntervals Generates a list of date intervals between two dates.

type SegmentedDateInterval

type SegmentedDateInterval struct {
	ID       int64
	Interval *DateInterval
}

SegmentedDateInterval struct represents an date interval with a segment ID to track what segment the date interval belongs to.

func RandomSegmentedDateIntervals

func RandomSegmentedDateIntervals(startDate time.Time, endDate time.Time, maxSeconds int64, totalSegments int64) []*SegmentedDateInterval

RandomSegmentedDateIntervals Generates a segmented list of date intervals between two dates.

type TimeRange

type TimeRange struct {
	Start time.Time
	End   time.Time
}

func DailyRangeForNow

func DailyRangeForNow(now func() time.Time) *TimeRange

DailyRangeForNow (TODO: Write detailed description)

func DailyRangeForTime

func DailyRangeForTime(dt time.Time) *TimeRange

DailyRangeForTime (TODO: Write detailed description)

func DailyRangesBetweenTimes

func DailyRangesBetweenTimes(start time.Time, end time.Time) []*TimeRange

DailyRangesBetweenTimes (TODO: Write detailed description)

func HourlyRangeForNow

func HourlyRangeForNow(now func() time.Time) *TimeRange

HourlyRangeForNow (TODO: Write detailed description)

func HourlyRangeForTime

func HourlyRangeForTime(dt time.Time) *TimeRange

HourlyRangeForTime function will take a date value and return two date times: (1) The first date time will take the date and discard the minutes, so for example if you give 12:30 PM then it will return 12:00 PM. (2) The second date time will disacrd the minutes and increase by 1 hour, for example if you give 12:30 PM then it will return 1:00 PM. Therefore the purpose of this function is to provide an hourly range for the inputted parameter. For example if I say 12:300 PM then this function will return 12:00 PM & 1:00 AM.

Developers Note: This would be useful to you if are building analytics engine which must group certain miunute based datapoints / timeseries into hours.

Here are some more examples to help you visualize: Monday Dec 18th - 9:30 AM --> (1) Monday Dec 18th - 9:00 AM and (2) Monday Dec 18th - 10:00 AM Monday Dec 18th - 5:10 PM --> (1) Monday Dec 18th - 5:00 PM and (2) Monday Dec 18th - 7:00 PM Monday Dec 18th - 10:55 PM --> (1) Monday Dec 18th - 10:00 PM and (2) Monday Dec 18th - 11:00 PM

func HourlyRangesBetweenTimes

func HourlyRangesBetweenTimes(start time.Time, end time.Time) []*TimeRange

HourlyRangesBetweenTimes (TODO: Write detailed description)

func ISOWeeklyRangeForNow

func ISOWeeklyRangeForNow(now func() time.Time) *TimeRange

ISOWeeklyRangeForNow (TODO: Write detailed description)

func ISOWeeklyRangeForTime

func ISOWeeklyRangeForTime(dt time.Time) *TimeRange

ISOWeeklyRangeForTime (TODO: Write detailed description)

func ISOWeeklyRangesBetweenTimes

func ISOWeeklyRangesBetweenTimes(start time.Time, end time.Time) []*TimeRange

ISOWeeklyRangesBetweenTimes (TODO: Write detailed description)

func MonthlyRangeForNow

func MonthlyRangeForNow(now func() time.Time) *TimeRange

MonthlyRangeForNow (TODO: Write detailed description)

func MonthlyRangeForTime

func MonthlyRangeForTime(dt time.Time) *TimeRange

MonthlyRangeForTime (TODO: Write detailed description)

func MonthlyRangesBetweenTimes

func MonthlyRangesBetweenTimes(start time.Time, end time.Time) []*TimeRange

MonthlyRangesBetweenTimes (TODO: Write detailed description)

func YearlyRangeForNow

func YearlyRangeForNow(now func() time.Time) *TimeRange

func YearlyRangeForTime

func YearlyRangeForTime(dt time.Time) *TimeRange

YearlyRangeForTime (TODO: Write detailed description)

func YearlyRangesBetweenTimes

func YearlyRangesBetweenTimes(start time.Time, end time.Time) []*TimeRange

YearlyRangesBetweenTimes (TODO: Write detailed description)

type TimeStepper

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

TimeStepper is a structure to hold keep track of the position we are in the datetime range which we are stepping through.

func NewTimeStepper

func NewTimeStepper(start time.Time, end time.Time, yearStep int, monthStep int, dayStep int, hourStep int, minuteStep int, secondStep int) *TimeStepper

NewTimeStepper is a constructor of the `TimeStepper` struct.

func (*TimeStepper) Done

func (ts *TimeStepper) Done() bool

Done checks to see if the stepper has stepped over the end datetime and will return true or false according.

func (*TimeStepper) Get

func (ts *TimeStepper) Get() time.Time

Get will return the value that that the stepper is currently on.

func (*TimeStepper) Next

func (ts *TimeStepper) Next() bool

Next makes one time step over and returns true or false depending if the stepper has stepped over the end datetime.

Jump to

Keyboard shortcuts

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