iso8601

package
v0.5.2 Latest Latest
Warning

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

Go to latest
Published: Dec 16, 2023 License: MIT Imports: 8 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func ParseDateTime

func ParseDateTime[bytes constraints.Bytes](b bytes, opts ...ParseDateTimeOptions) (time.Time, error)

ParseDateTime attempts to parse a given byte slice representing combined date, time, and optionally timezone offset in supported ISO 8601 formats. Supported formats include:

Basic                        Extended
20070301                     2007-03-01
2012W521                     2012-W52-1
2012Q485                     2012-Q4-85
20070301T1300Z               2007-03-01T13:00Z
20070301T1300Z               2007-03-01T13:00Z
20070301T1300+0100           2007-03-01T13:00+01:00
20070301T1300-0600           2007-03-01T13:00-06:00
20070301T130045Z             2007-03-01T13:00:45Z
20070301T130045+0100         2007-03-01T13:00:45+01:00
... and other combinations

The function returns a time.Time struct representing the parsed date-time, adjusted for the parsed timezone offset if provided.

In the absence of a time zone indicator, Parse returns a time in UTC.

When parsing a time with a zone offset like -0700, if the offset corresponds to a time zone used by the current location (Local), then Parse uses that location and zone in the returned time. Otherwise it records the time as being in a fabricated location with time fixed at the given zone offset.

If parsing fails, an error is returned.

Types

type Date

type Date struct {
	Year  int
	Month time.Month
	Day   int
}

Date represents a calendar date with year, month, and day components.

func DateOf added in v0.4.0

func DateOf(t time.Time) Date

DateOf returns the iso8601 Date in which a time occurs in that time's location.

func (Date) AddDays added in v0.4.0

func (d Date) AddDays(n int) Date

AddDays returns the date that is n days in the future. n can also be negative to go into the past.

func (Date) After added in v0.4.0

func (d Date) After(d2 Date) bool

After reports whether d occurs after d2.

func (Date) Before added in v0.4.0

func (d Date) Before(d2 Date) bool

Before reports whether d occurs before d2.

func (Date) Date

func (d Date) Date() Date

Date returns itself as it directly represents a date.

func (Date) DaysSince added in v0.4.0

func (d Date) DaysSince(s Date) (days int)

DaysSince returns the signed number of days between the date and s, not including the end day. This is the inverse operation to AddDays.

func (Date) In added in v0.4.0

func (d Date) In(loc *time.Location) time.Time

In returns the time corresponding to time 00:00:00 of the date in the location.

In is always consistent with time.Date, even when time.Date returns a time on a different day. For example, if loc is America/Indiana/Vincennes, then both

time.Date(1955, time.May, 1, 0, 0, 0, 0, loc)

and

iso8601.Date{Year: 1955, Month: time.May, Day: 1}.In(loc)

return 23:00:00 on April 30, 1955.

In panics if loc is nil.

func (Date) IsValid

func (d Date) IsValid() bool

IsValid checks if the date is valid based on its year, month, and day values.

func (Date) IsZero added in v0.4.0

func (d Date) IsZero() bool

IsZero reports whether date fields are set to their default value.

func (Date) MarshalText added in v0.4.0

func (d Date) MarshalText() ([]byte, error)

MarshalText implements the encoding.TextMarshaler interface. The output is the result of t.String().

func (Date) OrdinalDate added in v0.4.0

func (d Date) OrdinalDate() OrdinalDate

OrdinalDate converts a Date to an OrdinalDate. It calculates the day of the year for the given date.

func (Date) QuarterDate added in v0.4.0

func (d Date) QuarterDate() QuarterDate

QuarterDate converts a Date to a QuarterDate. It calculates the quarter of the year and the day within that quarter for the given date.

func (Date) StdTime

func (d Date) StdTime() time.Time

StdTime converts the Date structure to a time.Time object, using UTC for the time.

func (Date) String

func (d Date) String() string

String returns the ISO8601 string representation of the format "YYYY-MM-DD". For example: "2012-12-01".

func (*Date) UnmarshalText added in v0.4.0

func (d *Date) UnmarshalText(data []byte) error

UnmarshalText implements the encoding.TextUnmarshaler interface. The date is expected to be a string in a format accepted by ParseDate.

func (Date) Validate

func (d Date) Validate() error

Validate checks the individual components of the date (year, month, and day) and returns an error if any of them are out of the expected ranges.

func (Date) WeekDate added in v0.4.0

func (d Date) WeekDate() WeekDate

WeekDate converts a Date to a WeekDate. It calculates the week of the year and the day within that week for the given date.

type DateLike

type DateLike interface {
	// Date returns the underlying Date value.
	Date() Date

	// IsValid checks whether the date is valid.
	IsValid() bool

	// Validate checks the correctness of the date and returns an error if it's invalid.
	Validate() error
}

DateLike defines an interface for date-related structures. It provides methods for retrieving the date, validating the date, and checking if the date is valid.

func ParseDate

func ParseDate[bytes constraints.Bytes](b bytes) (DateLike, error)

ParseDate attempts to parse a given byte slice representing a date in various supported ISO 8601 formats. Supported formats include:

Basic           Extended
20121224        2012-12-24    Calendar date   (ISO 8601)
2012359         2012-359      Ordinal date    (ISO 8601)
2012W521        2012-W52-1    Week date       (ISO 8601)
2012Q485        2012-Q4-85    Quarter date

The function returns an implementation of DateLike or an error if the parsing fails.

type DateLikeRangeError

type DateLikeRangeError struct {
	Element string
	Value   int
	Year    int
	Min     int
	Max     int
}

DateLikeRangeError indicates that a value is not in an expected range for DateLike.

func (*DateLikeRangeError) Error

func (e *DateLikeRangeError) Error() string

Error implements the error interface.

type Duration

type Duration struct {
	Year        int
	Month       time.Month
	Week        int
	Day         int
	Hour        int
	Minute      int
	Second      int
	Millisecond int
	Microsecond int
	Nanosecond  int
	Negative    bool
}

Duration represents an ISO8601 duration with the maximum precision of nanoseconds. It includes components like years, months, weeks, days, hours, minutes, seconds, milliseconds, microseconds, and nanoseconds. The Negative field indicates whether the duration is negative.

func NewDuration

func NewDuration(d time.Duration) Duration

NewDuration makes ISO8601 Duration struct from time.Duration.

func ParseDuration

func ParseDuration[bytes constraints.Bytes](b bytes) (Duration, error)

ParseDuration attempts to parse a given byte slice representing a duration in the ISO 8601 format. Supported formats align with the regular expression patterns:

fraction:     (\d+)(?:[.,](\d{1,9}))?
durationTime: (?:${fraction}H)?(?:${fraction}M)?(?:${fraction}S)?
durationDate: (?:(\d+)Y)?(?:(\d+)M)?(?:(\d+)W)?(?:(\d+)D)?
duration:     ^([+-])?P${durationDate}(?:T(?!$)${durationTime})?$

Examples of valid durations include:

PnYnMnDTnHnMnS (e.g., P3Y6M4DT12H30M5S)
PnW (e.g., P4W)

According to the ISO 8601-1 standard, weeks are not allowed to appear together with any other units, and durations can only be positive. However, as extensions to the standard, ISO 8601-2 allows a sign character at the start of the string and permits combining weeks with other units. If using a string such as P3W1D, +P1M, or -P1M for interoperability, be aware that other programs may not recognize it.

The function returns a Duration structure or an error if the parsing fails.

func (Duration) IsZero

func (d Duration) IsZero() bool

IsZero checks duration is zero value.

func (Duration) Negate

func (d Duration) Negate() Duration

Negate changes the sign of the duration.

func (Duration) StdClockDuration added in v0.2.0

func (d Duration) StdClockDuration() time.Duration

StdClockDuration converts an ISO8601 Duration to a standard Go time.Duration. The conversion is calculated using hours, minutes, seconds, milliseconds, microseconds and nanoseconds.

func (Duration) StdDuration

func (d Duration) StdDuration() time.Duration

StdDuration converts the ISO8601 Duration to a standard Go time.Duration. Note: This conversion is an approximation. The duration of some components like years and months are averaged based on typical values:

  • 1 year is considered as 365.2425 days (or 31556952 seconds).
  • 1 month is considered as 30.44 days (or 2630016 seconds).
  • 1 week is considered as 7 days (or 604800 seconds).

func (Duration) String

func (d Duration) String() string

String returns the ISO8601 string representation of the duration. For example: "P1Y2M3DT4H5M6.007S".

type DurationRangeError added in v0.1.0

type DurationRangeError struct {
	Element string
	Value   int
	Min     int
	Max     int
}

DurationRangeError indicates that a value is not in an expected range for Duration.

func (*DurationRangeError) Error added in v0.1.0

func (e *DurationRangeError) Error() string

Error implements the error interface.

type Interval added in v0.1.0

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

Interval represents an ISO8601 time interval. It contains the start and end times, the duration of the interval, and the number of times the interval should be repeated.

func ParseInterval added in v0.1.0

func ParseInterval[bytes constraints.Bytes](b bytes) (Interval, error)

ParseInterval parses an ISO8601 time interval from a byte slice or string. It returns the parsed Interval and any error encountered.

func (Interval) Contains added in v0.1.0

func (i Interval) Contains(t time.Time) bool

Contains returns a boolean indicating whether the provided time.Time is between the Start or End dates as defined by this interval.

func (Interval) Duration added in v0.1.0

func (i Interval) Duration() Duration

Duration returns ISO 8601 duration.

func (Interval) End added in v0.1.0

func (i Interval) End() time.Time

End returns a time.Time representing the end time of the interval. If this interval has an explicit Start date specified, any existing relative Duration will be cleared.

Note: if the interval doesn't include a time component, the end time will actually be zero value (January 1, year 1, 00:00:00 UTC.) of the following day (since the interval covers the entire day).

func (Interval) Start added in v0.1.0

func (i Interval) Start() time.Time

Start returns a time.Time representing the beginning of this interval. If this interval has an explicit End date specified, any existing relative Duration will be cleared.

Note: if the interval doesn't include a time component, the start time will actually be zero value (January 1, year 1, 00:00:00 UTC.) of the following day (since the interval covers the entire day). Intervals include the start value (in contrast to the end value).

type IntervalRangeError added in v0.1.0

type IntervalRangeError struct {
	Element string
	Value   int
	Min     int
	Max     int
}

IntervalRangeError indicates that a value is not in an expected range for time interval.

func (*IntervalRangeError) Error added in v0.1.0

func (e *IntervalRangeError) Error() string

Error implements the error interface.

type OrdinalDate

type OrdinalDate struct {
	Year int
	Day  int
}

OrdinalDate represents a date specified by its year and the day-of-year (ordinal date), where the day-of-year ranges from 1 through 365 (or 366 in a leap year).

func (OrdinalDate) Date

func (o OrdinalDate) Date() Date

Date converts an OrdinalDate into the standard Date representation. It calculates the exact calendar date based on the year and the day-of-year.

func (OrdinalDate) IsValid

func (o OrdinalDate) IsValid() bool

IsValid checks if the ordinal date is valid based on its year and day-of-year values.

func (OrdinalDate) MarshalText added in v0.4.0

func (o OrdinalDate) MarshalText() ([]byte, error)

MarshalText implements the encoding.TextMarshaler interface. The output is the result of t.String().

func (OrdinalDate) String

func (o OrdinalDate) String() string

String returns the ISO8601 string representation of the format "YYYY-DDD". For example: "2012-359".

func (*OrdinalDate) UnmarshalText added in v0.4.0

func (o *OrdinalDate) UnmarshalText(data []byte) error

UnmarshalText implements the encoding.TextUnmarshaler interface. The week date is expected to be a string in a format accepted by ParseDate.

func (OrdinalDate) Validate

func (o OrdinalDate) Validate() error

Validate checks the individual components of the ordinal date (year and day-of-year) and returns an error if any of them are out of the expected ranges.

type ParseDateTimeOptions

type ParseDateTimeOptions func(*parseDateTimeOptions)

ParseDateTimeOptions is a function type that modifies the parsing behavior of a datetime string. It acts as a functional option.

func WithInLocation added in v0.0.6

func WithInLocation(loc *time.Location) ParseDateTimeOptions

WithInLocation is an options to interpret the time as in the given location.

By default, if no location is set, the parser uses current location (Local).

func WithTimeDesignators

func WithTimeDesignators(designators ...byte) ParseDateTimeOptions

WithTimeDesignators is an option that modifies the set of valid characters which can be used as time designators when parsing a datetime string.

By default, if no designators are set, the parser uses only 'T'.

type QuarterDate

type QuarterDate struct {
	Year    int
	Quarter int
	Day     int
}

QuarterDate represents a date within a specific quarter of a year. It includes the year, quarter (from 1 to 4), and day within that quarter.

func (QuarterDate) Date

func (q QuarterDate) Date() Date

Date converts a QuarterDate into the standard Date representation. It calculates the exact calendar date based on the year, quarter, and day within that quarter.

func (QuarterDate) IsValid

func (q QuarterDate) IsValid() bool

IsValid checks if the quarter date is valid based on its year, quarter, and day within the quarter values.

func (QuarterDate) MarshalText added in v0.4.0

func (q QuarterDate) MarshalText() ([]byte, error)

MarshalText implements the encoding.TextMarshaler interface. The output is the result of t.String().

func (QuarterDate) String

func (q QuarterDate) String() string

String returns the ISO8601 string representation of the format "YYYY-QX-DD". For example: "2012-Q4-85".

func (*QuarterDate) UnmarshalText added in v0.4.0

func (q *QuarterDate) UnmarshalText(data []byte) error

UnmarshalText implements the encoding.TextUnmarshaler interface. The quarter date is expected to be a string in a format accepted by ParseDate.

func (QuarterDate) Validate

func (q QuarterDate) Validate() error

Validate checks the individual components of the quarter date (year, quarter, and day within the quarter) and returns an error if any of them are out of the expected ranges.

type Time

type Time struct {
	Hour       int // The hour values between 0 and 23 inclusive, with an exception for the '24:00:00' time.
	Minute     int // The minute of the hour; range [0-59]
	Second     int // The second of the minute; range [0-59]
	Nanosecond int // The nanosecond of the second; range [0-999999999]
}

Time represents an ISO8601-compliant time without a date, specified by its hour, minute, second, and nanosecond.

Note: The time '24:00:00' is valid and represents midnight at the end of the given day.

func ParseTime

func ParseTime[bytes constraints.Bytes](b bytes) (Time, error)

ParseTime attempts to parse a given byte slice representing a time in various supported ISO 8601 formats. Supported formats include:

Basic              Extended
12                 N/A
12.123456789       N/A
12,123456789       N/A
1230               12:30
1230.123456789     12:30.123456789
1230,123456789     12:30,123456789
123045             12:30:45
123045.123456789   12:30:45.123456789
123045,123456789   12:30:45,123456789

The function returns a Time structure or an error if the parsing fails.

func TimeOf added in v0.4.0

func TimeOf(t time.Time) Time

TimeOf returns the Time representing the time of day in which a time occurs in that time's location. It ignores the date.

func (Time) After added in v0.4.0

func (t Time) After(t2 Time) bool

After reports whether t occurs after t2.

func (Time) Before added in v0.4.0

func (t Time) Before(t2 Time) bool

Before reports whether t occurs before t2.

func (Time) IsZero added in v0.4.0

func (t Time) IsZero() bool

IsZero reports whether time fields are set to their default value.

func (Time) MarshalText added in v0.4.0

func (t Time) MarshalText() ([]byte, error)

MarshalText implements the encoding.TextMarshaler interface. The output is the result of t.String().

func (Time) String

func (t Time) String() string

String returns the ISO8601 string representation of the format "hh:mm:dd". For example: "12:59:59.123456789".

func (*Time) UnmarshalText added in v0.4.0

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

UnmarshalText implements the encoding.TextUnmarshaler interface. The time is expected to be a string in a format accepted by ParseTime.

func (Time) Validate

func (t Time) Validate() error

Validate checks the individual components of the time (hour, minute, second, and nanosecond) against their respective valid ISO8601 ranges.

Specifically, it validates:

  • Hour values between 0 and 23 inclusive, with an exception for the '24:00:00' time.
  • Minute values between 0 and 59 inclusive.
  • Second values between 0 and 59 inclusive.
  • Nanosecond values range [0-999999999]

Returns an error if any of the components are out of their expected ranges.

type TimeRangeError

type TimeRangeError struct {
	Element string
	Value   int
	Min     int
	Max     int
}

TimeRangeError indicates that a value is not in an expected range for Time.

func (*TimeRangeError) Error

func (e *TimeRangeError) Error() string

Error implements the error interface.

type TimeZoneRangeError

type TimeZoneRangeError struct {
	Element string
	Value   int
	Min     int
	Max     int
}

TimeRangeError indicates that a value is not in an expected range for Time.

func (*TimeZoneRangeError) Error

func (e *TimeZoneRangeError) Error() string

Error implements the error interface.

type UnexpectedTokenError

type UnexpectedTokenError struct {
	Value      string
	Token      string
	AfterToken string
	Expected   string
}

UnexpectedTokenError represents an error encountered when an unexpected token is detected during parsing. This error provides details about the token that was unexpected, any preceding token, and what was expected in its place.

func (*UnexpectedTokenError) Error

func (u *UnexpectedTokenError) Error() string

Error implements the error interface.

type WeekDate

type WeekDate struct {
	Year int
	Week int
	Day  int
}

WeekDate represents a date within a specific week of a given year, following the ISO 8601 week-date system. It includes the year, week number (1 to 52 or 53), and day of the week (1 for Monday to 7 for Sunday).

func (WeekDate) Date

func (w WeekDate) Date() Date

Date converts a WeekDate into the standard Date representation. It calculates the exact calendar date based on the year, week number, and day of the week.

func (WeekDate) IsValid

func (w WeekDate) IsValid() bool

IsValid checks if the week date is valid based on its year, week number, and day of the week values.

func (WeekDate) MarshalText added in v0.4.0

func (w WeekDate) MarshalText() ([]byte, error)

MarshalText implements the encoding.TextMarshaler interface. The output is the result of t.String().

func (WeekDate) String

func (w WeekDate) String() string

String returns the ISO8601 string representation of the format "YYYY-WX-DD". For example: "2012-W52-1".

func (*WeekDate) UnmarshalText added in v0.4.0

func (w *WeekDate) UnmarshalText(data []byte) error

UnmarshalText implements the encoding.TextUnmarshaler interface. The week date is expected to be a string in a format accepted by ParseDate.

func (WeekDate) Validate

func (w WeekDate) Validate() error

Validate checks the individual components of the week date (year, week number, and day of the week) and returns an error if any of them are out of the expected ranges.

type Zone

type Zone struct {
	Hour     int
	Minute   int
	Second   int
	Negative bool
}

Zone represents an ISO8601-compliant timezone offset, specified by its hour, minute, and second components. The "Negative" field indicates whether the offset is behind (true) or ahead (false) of Coordinated Universal Time (UTC).

func ParseZone

func ParseZone[bytes constraints.Bytes](b bytes) (Zone, error)

ParseZone attempts to parse a given byte slice representing a timezone offset in various supported ISO 8601 formats. Supported formats include:

Basic       Extended
Z           N/A
±hh         N/A
±hhmm       ±hh:mm
±hhmmss     ±hh:mm:ss

The function returns a Zone structure or an error if the parsing fails.

func (Zone) Offset

func (z Zone) Offset() int

Offset computes the total time offset in seconds for the Zone. This value is positive if the zone is ahead of UTC, and negative if it's behind. It takes into account the hour, minute, second, and Negative fields.

func (Zone) Validate

func (z Zone) Validate() error

Validate checks the individual components of the timezone offset (hour, minute, and second) against their respective valid ISO8601 ranges.

Specifically, it validates:

  • Minute values between 0 and 99 inclusive.
  • Second values between 0 and 99 inclusive.
  • Hour values between 0 and 99 inclusive.

Returns an error if any of the components are out of their expected ranges.

Jump to

Keyboard shortcuts

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