dates

package
v1.2.0 Latest Latest
Warning

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

Go to latest
Published: May 2, 2024 License: MIT Imports: 9 Imported by: 0

Documentation

Overview

Package dates provides utilities for parsing, formatting, and manipulating dates and times. It includes functions to parse dates with or without time zones, handle date ranges, and convert dates to various formats. It also defines constants for different time precisions and initializes default time zones and date formats.

Package dates provides helper functions for date and time parsing.

Index

Constants

View Source
const (
	YearPrecision        = "year"        // Represents year precision
	MonthPrecision       = "month"       // Represents month precision
	DayPrecision         = "day"         // Represents day precision
	HourPrecision        = "hour"        // Represents hour precision
	MinutePrecision      = "minute"      // Represents minute precision
	SecondPrecision      = "second"      // Represents second precision
	MillisecondPrecision = "millisecond" // Represents millisecond precision
	MicrosecondPrecision = "microsecond" // Represents microsecond precision
	NanosecondPrecision  = "nanosecond"  // Represents nanosecond precision
)

Constants for different time precisions

Variables

View Source
var DefaultTZ *time.Location

DefaultTZ is a pointer to a time.Location that stores the default timezone.

View Source
var PreferredTimeStringTimezone = "America/New_York"

PreferredTimezone represents the preferred timezone for time display.

View Source
var TimeStringDateFormat = "2006-01-02"

DateFormat specifies the format for displaying date-only information.

View Source
var TimeStringTimeFormat = "2006-01-02 15:04:05 Z07:00"

TimeFormat specifies the format for displaying full datetime information.

Functions

func Earliest

func Earliest(dates ...interface{}) (time.Time, error)

func FromExcelTime

func FromExcelTime(excelTime float64, tz *time.Location) (time.Time, error)

FromExcelTime converts Excel time, which is the number of days since 1900-01-01, to a time.Time. The function takes the Excel time as a float64 and an optional timezone. If no timezone is provided, it uses the default timezone.

func GenerateDailyDateKeys

func GenerateDailyDateKeys(startDate, endDate time.Time) []string

GenerateDailyDateKeys generates a list of date keys for each day between the start and end dates. The date keys are in the format "YYYY-MM-DD". The function includes the end date in the list of keys. The start and end dates should be in the same timezone.

func GenerateDateKeys

func GenerateDateKeys(start, end time.Time, keyType string) ([]string, error)

GenerateDateKeys generates a list of date keys between the provided start and end dates based on the provided keyType. The keyType can be "days", "weeks", "months", or "years". If the keyType is not recognized, the function returns an error. The function returns a slice of strings, each representing a date key, and an error.

func GenerateMonthlyDateKeys

func GenerateMonthlyDateKeys(startDate, endDate time.Time) []string

GenerateMonthlyDateKeys generates a list of date keys for each month between the start and end dates. The date keys are in the format "YYYY-MM". The function includes the end date's month in the list of keys. The start and end dates should be in the same timezone.

func GenerateWeeklyDateKeys

func GenerateWeeklyDateKeys(startDate, endDate time.Time) []string

GenerateWeeklyDateKeys generates a list of date keys for each week between the start and end dates. The date keys are in the format "YYYY-Www", where YYYY is the year and ww is the week number. The function includes the end date in the list of keys. The start and end dates should be in the same timezone. The start date is adjusted to the start of its week (Sunday) and the end date is adjusted to the end of its week (Saturday). If the start date is in the first week of the year, it is set to January 1st. If the end date is in the last week of the year, it is set to December 31st.

func GenerateYearlyDateKeys

func GenerateYearlyDateKeys(startDate, endDate time.Time) []string

GenerateYearlyDateKeys generates a list of date keys for each year between the start and end dates. The date keys are in the format "YYYY", where YYYY is the year. The function includes the end date in the list of keys. The start and end dates should be in the same timezone. The start date is adjusted to the start of its year (January 1st) and the end date is adjusted to the start of the next year. The function returns a slice of strings, each representing a date key for a year.

func GetDateKeyType

func GetDateKeyType(dateKey string) (string, error)

GetDateKeyType identifies the type of the date key. It accepts a date key of type string. The function returns the type of the date key and any errors that occurred during the identification. The possible types are "days", "months", "years", and "weeks". If the date key is not valid or its type is unknown, an error is returned.

func IsStartOfDay added in v1.0.0

func IsStartOfDay(t time.Time, loc *time.Location) bool

IsStartOfDay checks if the given time is at the start of the day in the specified timezone.

func IsValidDateKey

func IsValidDateKey(dateKey string) bool

IsValidDateKey checks if the provided date key is valid. It accepts a date key of type string. The function returns true if the date key is valid, false otherwise.

func Latest

func Latest(dates ...interface{}) (time.Time, error)

func ParseDateInput

func ParseDateInput(dateInput interface{}, tz ...*time.Location) (time.Time, string, error)

ParseDateInput tries to parse the dateInput in various formats. It returns the parsed time, the precision, and any error encountered.

func TimeString added in v1.1.0

func TimeString(t time.Time) string

TimeString converts a time.Time object to a string representation using a predefined timezone and format. This method is primarily used in for string methods that need a standardized string representation of time.Time, such as for logging, displaying to users, or when performing date-time comparisons in a specific timezone.

Parameters

  • time.Time: The time object to be formatted.

Returns

  • string: The formatted time as a string in the predefined timezone and format. Returns 'nil' if the time object is a zero value.

Notes

  • This method utilizes the global PreferredTimezone variable, which can be set to the preferred timezone or falls back to UTC if the preferred timezone is not set.

func ToDayString

func ToDayString(dateInput interface{}, tz ...*time.Location) (string, error)

ToDayString takes an interface and returns the date in YYYY-MM-DD format and an error

func ToExcelTime

func ToExcelTime(t time.Time, tz *time.Location) float64

ToExcelTime converts a time.Time to Excel time, which is the number of days since 1900-01-01. The function returns the Excel time as a float64. The function now takes a timezone as input and adjusts the Excel timestamp based on the timezone of the time.Time object.

func ToTime

func ToTime(dateInput interface{}, tz ...*time.Location) (time.Time, error)

ToTime takes an interface and returns just the time.Time and an error

Types

type DateRange

type DateRange struct {
	StartDate time.Time
	EndDate   time.Time
}

DateRange represents a range of dates with a start and end date.

func CombineDateRanges

func CombineDateRanges(dates ...interface{}) (DateRange, error)

CombineDateRanges is a function that takes multiple DateRange objects or a slice of DateRange objects and uses the Earliest and Latest functions to generate a new DateRange object that covers the entire time range of the original objects.

func DateKeyToDateRange

func DateKeyToDateRange(dateKey string, tz ...*time.Location) (*DateRange, error)

DateKeyToDateRange creates a new DateRange instance from a date key. It accepts a date key of type string and an optional time zone. If the time zone is not provided, the default time zone is used. The function returns a pointer to the new DateRange instance and any errors that occurred during the creation.

func FromDailyDateKey

func FromDailyDateKey(key string, loc *time.Location) (DateRange, error)

FromDailyDateKey converts a date key into a DateRange. The date key is expected to be in the format "YYYY-MM-DD". The function returns a DateRange with the StartDate and EndDate being the same day. If the key is not in the expected format or contains invalid date components, an error is returned.

func FromMonthlyDateKey

func FromMonthlyDateKey(key string, loc *time.Location) (DateRange, error)

FromMonthlyDateKey converts a date key into a DateRange. The date key is expected to be in the format "YYYY-MM". The function returns a DateRange with the StartDate being the first day of the month and the EndDate being the last day of the same month. If the key is not in the expected format or contains invalid date components, an error is returned.

func FromWeeklyDateKey

func FromWeeklyDateKey(key string, loc *time.Location) (DateRange, error)

FromWeeklyDateKey takes a date key and a location as input and returns a DateRange and an error. The date key should be in the format "YYYY-Www", where YYYY is the year and ww is the week number (e.g., 2020-W01). The location is used to set the timezone for the start and end dates in the DateRange. The function calculates the start and end dates of the week specified in the date key. The start date is the Sunday of the week and the end date is the Saturday of the week. If the date key is not in the correct format or if the week number is not between 1 and 53, the function returns an error.

func FromYearlyDateKey

func FromYearlyDateKey(key string, loc *time.Location) (DateRange, error)

FromYearlyDateKey converts a date key into a DateRange. The date key is expected to be in the format "YYYY". The function returns a DateRange with the StartDate being the first day of the year and the EndDate being the last day of the same year. If the key is not in the expected format or contains an invalid year, an error is returned.

func GetDateRange

func GetDateRange(defaultTZ *time.Location, dateInput, fromInput, toInput string) (DateRange, error)

GetDateRange is a function that takes in a timezone, dateInput, fromInput, and toInput as strings. It returns a DateRange and an error. The function converts the date inputs to a DateRange, and returns the DateRange and any errors that occurred during the conversion.

func NewDateRange

func NewDateRange(startDate, endDate interface{}, defaultTZ ...*time.Location) (*DateRange, error)

NewDateRange is a function that creates a new DateRange instance. It accepts two parameters for the start and end dates, which can be of type time.Time or string. An optional time zone can be provided as the third parameter. If not provided, the default time zone is used. The function returns a pointer to the new DateRange instance and any errors that occurred during the creation.

func StopwatchStart

func StopwatchStart() *DateRange

func (*DateRange) Contains

func (dr *DateRange) Contains(t interface{}) bool

Contains checks if the provided time or DateRange (the argument) is wholly contained within the DateRange on which the method is called (the reference DateRange).

func (*DateRange) DoesNotContain

func (dr *DateRange) DoesNotContain(t interface{}) bool

DoesNotContain checks if the provided time or DateRange (the argument) is entirely outside the DateRange on which the method is called (the reference DateRange).

func (*DateRange) Duration

func (dr *DateRange) Duration() time.Duration

Duration returns the duration of the DateRange.

func (*DateRange) DurationInMs

func (dr *DateRange) DurationInMs() (int, error)

DurationInMs returns the duration of the DateRange in milliseconds. It throws an error if either the start or end date is null.

func (*DateRange) GenerateDateKeys

func (dr *DateRange) GenerateDateKeys(keyType string) ([]string, error)

GenerateDateKeys generates a list of date keys for a DateRange based on the provided keyType. The keyType can be "days", "weeks", "months", or "years". The function uses the StartDate and EndDate of the DateRange to generate the keys. If the keyType is not recognized, the function returns an empty slice. The function returns a slice of strings, each representing a date key.

func (*DateRange) IsEarlierThan

func (dr *DateRange) IsEarlierThan(date interface{}) (bool, error)

IsEarlierThan is a method that takes a parameter of type interface. It converts the parameter to a Time when necessary and compares if the start date of the value is earlier than the start date of our reference DateRange.

func (*DateRange) IsLaterThan

func (dr *DateRange) IsLaterThan(date interface{}) (bool, error)

IsLaterThan is a method that takes a parameter of type interface. It converts the parameter to a Time when necessary and compares if the end date of the DateRange is later than the end date of the parameter passed.

func (*DateRange) PartiallyContains

func (dr *DateRange) PartiallyContains(other DateRange) bool

PartiallyContains checks if the provided DateRange (the argument) partially intersects with the DateRange on which the method is called (the reference DateRange).

func (*DateRange) SetDates

func (dr *DateRange) SetDates(startDate, endDate interface{}, defaultTZ ...*time.Location) error

SetDates sets the start and end dates of the DateRange. It accepts two parameters for the start and end dates, which can be of type time.Time or string. If the dates are strings, they are parsed using the ParseDateInput function. An optional time zone can be provided as the third parameter. If not provided, the default time zone is used. The function returns an error if the start or end date is invalid or if they cannot be parsed.

func (*DateRange) SetFromDateKey

func (dr *DateRange) SetFromDateKey(key string, loc *time.Location) error

SetFromDateKey sets the DateRange from a date key. The date key can be in the format "YYYY-Www" for weekly, "YYYY-MM-DD" for daily, "YYYY-MM" for monthly, or "YYYY" for yearly. The function uses the provided location to set the timezone for the start and end dates in the DateRange. If the date key is not in the correct format or contains invalid date components, the function returns an error.

func (*DateRange) StopwatchEnd

func (dr *DateRange) StopwatchEnd()

func (*DateRange) StopwatchStart

func (dr *DateRange) StopwatchStart()

func (DateRange) String

func (dr DateRange) String() string

func (*DateRange) UnixTimestamps

func (dr *DateRange) UnixTimestamps() (int64, int64)

UnixTimestamps returns the start and end dates as Unix timestamps.

func (*DateRange) ValidateTimestamps

func (dr *DateRange) ValidateTimestamps(timestamps ...int64) (validTimestamps, invalidTimestamps []int64)

ValidateTimestamps checks if the provided timestamps are contained within the current DateRange. It returns two slices of timestamps: the first one contains valid timestamps, the second one contains invalid timestamps.

type RegexType

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

RegexType is used for storing a regular expression and the timeUnit it parses to.

type TimeFormats

type TimeFormats struct {
	Format    string // The time format
	Precision string // The precision of the time format
	Timezone  bool   // Whether the time format includes a timezone
}

TimeFormats is a struct that holds information about a time format. Format is a string that represents the time format. Precision is a string that represents the precision of the time format. Timezone is a boolean that indicates whether the time format includes a timezone.

type TimeInterval

type TimeInterval struct {
	Duration      time.Duration
	IntervalType  string
	IntervalValue int
}

TimeInterval represents a duration object

func (*TimeInterval) SetInterval

func (ti *TimeInterval) SetInterval(interval string) error

Jump to

Keyboard shortcuts

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