date

package module
v2.0.12-beta Latest Latest
Warning

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

Go to latest
Published: May 1, 2024 License: BSD-3-Clause Imports: 13 Imported by: 3

README

date

GoDoc Build Status Coverage Status Go Report Card Issues

Package date provides functionality for working with dates.

This package introduces a light-weight Date type that is storage-efficient and convenient for calendrical calculations and date parsing and formatting (including years outside the [0,9999] interval).

It also provides

  • clock.Clock which expresses a wall-clock style hours-minutes-seconds with millisecond precision.
  • timespan.DateRange which expresses a period between two dates.
  • timespan.TimeSpan which expresses a duration of time between two instants (see RFC5545).
  • view.VDate which wraps Date for use in templates etc.

See package documentation for full documentation and examples.

See also period.Period, which implements periods corresponding to the ISO-8601 form (e.g. "PT30S").

Installation

go get github.com/rickb777/date/v2

Status

This library has been in reliable production use for some time. Versioning follows the well-known semantic version pattern.

Version 2

Changes since v1:

  • The period.Period type has moved.
  • clock.Clock now has nanosecond resolution (formerly millisecond resolution).
  • date.Date is now an integer that holds the number of days since year zero. Previously, it was a struct based on year 1970.
  • date.Date time conversion methods have more explicit names - see table below.
  • date.Date arithmetic and comparison operations now rely on Go operators; the corresponding methods have been deleted - see table below.
  • date.Date zero value is now year 0 (Gregorian proleptic astronomical) so 1970 will no longer cause issues.
  • date.PeriodOfDays has been moved to timespan.PeriodOfDays
  • date.DateString has been deleted; the SQL driver.Valuer implementation is now pluggable and serves the same purpose more simply.

Renamed methods:

Was Use instead
date.Date.Local date.Date.Midnight
date.Date.UTC date.Date.MidnightUTC
date.Date.In date.Date.MidnightIn

Deleted methods and functions:

Was Use instead
date.Date.Add +
date.Date.Sub -
date.Date.IsZero == 0
date.Date.Equal ==
date.Date.Before <
date.Date.After >
date.IsLeap gregorian.IsLeap
date.DaysIn gregorian.DaysIn
timespan.DateRange.Normalise (not needed)

Any v1 dates persistently stored as integers will be incorrect; these can be corrected by adding 719162 (date.ZeroOffset) to them, which is the number of days between year zero (v2) and 1970 (v1). Dates stored as strings will be unaffected.

Credits

This package follows very closely the design of package time in the standard library; many of the Date methods are implemented using the corresponding methods of the time.Time type and much of the documentation is copied directly from that package.

The original Good Work on which this was based was done by Filippo Tampieri at Fxtlabs.

Documentation

Overview

Package date provides functionality for working with dates. It implements a light-weight Date type that is storage-efficient and convenient for calendrical calculations and date parsing and formatting (including years outside the [0,9999] interval).

Subpackages provide:

* `clock.Clock` which expresses a wall-clock style hours-minutes-seconds with millisecond precision.

* `timespan.DateRange` which expresses a period between two dates.

* `timespan.TimeSpan` which expresses a duration of time between two instants.

* `view.VDate` which wraps `Date` for use in templates etc.

Credits

This package follows very closely the design of package time (http://golang.org/pkg/time/) in the standard library, many of the Date methods are implemented using the corresponding methods of the time.Time type, and much of the documentation is copied directly from that package.

References

https://golang.org/src/time/time.go

https://en.wikipedia.org/wiki/Gregorian_calendar

https://en.wikipedia.org/wiki/Proleptic_Gregorian_calendar

https://en.wikipedia.org/wiki/Astronomical_year_numbering

https://en.wikipedia.org/wiki/ISO_8601

https://tools.ietf.org/html/rfc822

https://tools.ietf.org/html/rfc850

https://tools.ietf.org/html/rfc1123

https://tools.ietf.org/html/rfc3339

Index

Examples

Constants

View Source
const (
	// Zero is the named zero value for Date and corresponds to Monday, January 1,
	// year 1 AD in the proleptic Gregorian calendar.
	// This is the same zero as used by time.Time.
	Zero Date = 0

	// ZeroDay was the day of 1st January year 1 AD.
	ZeroDay = time.Monday

	// ZeroOffset is the number of days between 0001-01-01 and 1970-01-01, using the
	// proleptic Gregorian calendar. It is based on the same Unix calculation as used
	// by time.Time.
	//
	// It is similar to the "Rata Die" numbering system, for which the offset would
	// be 719163 instead.
	ZeroOffset = 719162
)
View Source
const (
	ISO8601  = "2006-01-02" // ISO 8601 extended format
	ISO8601B = "20060102"   // ISO 8601 basic format
	RFC822   = "02-Jan-06"
	RFC822W  = "Mon, 02-Jan-06" // RFC822 with day of the week
	RFC850   = "Monday, 02-Jan-06"
	RFC1123  = "02 Jan 2006"
	RFC1123W = "Mon, 02 Jan 2006" // RFC1123 with day of the week
	RFC3339  = "2006-01-02"
)

These are predefined layouts for use in Date.Format and Date.Parse. The reference date used in the layouts is the same date used by the time package in the standard library:

Monday, Jan 2, 2006

To define your own format, write down what the reference date would look like formatted your way; see the values of the predefined layouts for examples. The model is to demonstrate what the reference date looks like so that the Parse function and Format method can apply the same transformation to a general date value.

Variables

View Source
var DaySuffixes = []string{
	"st", "nd", "rd", "th", "th",
	"th", "th", "th", "th", "th",
	"th", "th", "th", "th", "th",
	"th", "th", "th", "th", "th",
	"st", "nd", "rd", "th", "th",
	"th", "th", "th", "th", "th",
	"st",
}

DaySuffixes is the default array of strings used as suffixes when a format string contains "nd" (as in "second"). This can be altered at startup in order to change the default locale strings used for formatting dates. It supports every locale that uses the Gregorian calendar and has a suffix after the day-of-month number.

View Source
var Valuer = ValueAsString

Valuer is the pluggable implementation function for converting dates to driver.Value. It is initialised with ValueAsString.

Functions

func ValueAsInt

func ValueAsInt(d Date) (driver.Value, error)

ValueAsInt converts a date for DB storage using an integer.

func ValueAsString

func ValueAsString(d Date) (driver.Value, error)

ValueAsString converts a date for DB storage using an string.

Types

type Date

type Date int64

A Date represents a date under the proleptic Gregorian calendar as used by ISO 8601. This calendar uses astronomical year numbering, so it includes a year 0 and represents earlier years as negative numbers (i.e. year 0 is 1 BC; year -1 is 2 BC, and so on).

A Date is a 64-bit integer, so the total range is huge.

Programs using dates should typically store and pass them as values, not pointers. That is, date variables and struct fields should be of type date.Date, not *date.Date unless the pointer indicates an optional value. A Date value can be used by multiple goroutines simultaneously.

Date values can be compared using the ==, !=, >, >=, <, and <= operators.

Because a Date is a number of days since Zero, + and - operations add or subtract some number of days.

The zero value of Date is equivalent to the zero value of time.Time; the zero value of time.Time is January 1, year 1, 00:00:00.000000000 UTC.

Date does not distinguish between official Gregorian dates and earlier proleptic dates, which can also be represented when needed.

Although the first official date of the Gregorian calendar was Friday, October 15th 1582, this is unrelated to the Unix epoch or day 0 used here. However, for a date before 1582 to be meaningful, it must be clarified separately whether it is a proleptic Gregorian date, or a Julian date, or some other.

func AutoParse

func AutoParse(value string) (Date, error)

AutoParse is like ParseISO, except that it automatically adapts to a variety of date formats provided that they can be detected unambiguously. Specifically, this includes the widely-used "European" and "British" date formats but not the common US format. Surrounding whitespace is ignored.

The supported formats are:

* all formats supported by ParseISO

* yyyy/mm/dd | yyyy.mm.dd (or any similar pattern)

* dd/mm/yyyy | dd.mm.yyyy (or any similar pattern)

* d/m/yyyy | d.m.yyyy (or any similar pattern)

* surrounding whitespace is ignored

func AutoParseUS

func AutoParseUS(value string) (Date, error)

AutoParseUS is like ParseISO, except that it automatically adapts to a variety of date formats provided that they can be detected unambiguously. Specifically, this includes the widely-used "European" and "US" date formats but not the common "British" format. Surrounding whitespace is ignored.

The supported formats are:

* all formats supported by ParseISO

* yyyy/mm/dd | yyyy.mm.dd (or any similar pattern)

* mm/dd/yyyy | mm.dd.yyyy (or any similar pattern)

* m/d/yyyy | m.d.yyyy (or any similar pattern)

* surrounding whitespace is ignored

func Max

func Max() Date

Max returns the largest representable date, which is nearly 6 million years in the future.

Example
d := Max()
fmt.Println(d)
Output:

+5877642-07-12

func Min

func Min() Date

Min returns the smallest representable date, which is nearly 6 million years in the past.

Example
d := Min()
fmt.Println(d)
Output:

-5879610-06-24

func MustAutoParse

func MustAutoParse(value string) Date

MustAutoParse is as per AutoParse except that it panics if the string cannot be parsed. This is intended for setup code; don't use it for user inputs.

func MustAutoParseUS

func MustAutoParseUS(value string) Date

MustAutoParseUS is as per AutoParseUS except that it panics if the string cannot be parsed. This is intended for setup code; don't use it for user inputs.

func MustParse

func MustParse(layout, value string) Date

MustParse is as per Parse except that it panics if the string cannot be parsed. This is intended for setup code; don't use it for user inputs.

func MustParseISO

func MustParseISO(value string) Date

MustParseISO is as per ParseISO except that it panics if the string cannot be parsed. This is intended for setup code; don't use it for user inputs.

func New

func New(year int, month time.Month, day int) Date

New returns the Date value corresponding to the given year, month, and day.

The month and day may be outside their usual ranges and will be normalized during the conversion.

Example
d := New(9999, time.December, 31)
fmt.Printf("%s (day %d) is a long time in the future but calendars don't stop then.\n", d, d)
Output:

9999-12-31 (day 3652058) is a long time in the future but calendars don't stop then.

func NewAt

func NewAt(t time.Time) Date

NewAt returns the Date value corresponding to the given time. Note that the date is relative to the time zone specified by the given Time value.

func Parse

func Parse(layout, value string) (Date, error)

Parse parses a formatted string of a known layout and returns the Date value it represents. The layout defines the format by showing how the reference date, defined to be

Monday, Jan 2, 2006

would be interpreted if it were the value; it serves as an example of the input format. The same interpretation will then be made to the input string.

This function actually uses time.Parse to parse the input and can use any layout accepted by time.Parse, but returns only the date part of the parsed Time value.

This function cannot currently parse ISO 8601 strings that use the expanded year format; you should use date.ParseISO to parse those strings correctly. That is, it only accepts years represented with exactly four digits.

Example
// longForm shows by example how the reference date would be
// represented in the desired layout.
const longForm = "Mon, January 2, 2006"
d, _ := Parse(longForm, "Thu, February 14, 2013")
fmt.Println(d)

// shortForm is another way the reference date would be represented.
const shortForm = "2006-Jan-02"
d, _ = Parse(shortForm, "2013-Feb-14")
fmt.Println(d)

// usForm is a typical US way the reference date would be represented.
const usForm = "01/02/2006"
d, _ = Parse(usForm, "02/14/2013")
fmt.Println(d)
Output:

2013-02-14
2013-02-14
2013-02-14

func ParseISO

func ParseISO(value string) (Date, error)

ParseISO parses an ISO 8601 formatted string and returns the date value it represents. It accepts the following formats:

  • the common formats ±YYYY-MM-DD and ±YYYYMMDD (e.g. 2006-01-02 and 20060102)
  • the ordinal date representation ±YYYY-OOO (e.g. 2006-217)

For common formats, ParseISO will accept dates with more year digits than the four-digit minimum. A leading plus '+' sign is allowed and ignored. Basic format (without '-' separators) is allowed.

For ordinal dates, the extended format (including '-') is supported, but the basic format (without '-') is not supported because it could not be distinguished from the YYYYMMDD format.

See also date.Parse, which can be used to parse date strings in other formats; however, it only accepts years represented with exactly four digits.

Background: https://en.wikipedia.org/wiki/ISO_8601#Dates https://www.iso.org/obp/ui#iso:std:iso:8601:-1:ed-1:v1:en:term:3.1.3.1

Example
d, _ := ParseISO("+12345-06-07")
year, month, day := d.Date()
fmt.Println(year)
fmt.Println(month)
fmt.Println(day)
Output:

12345
June
7

func Today

func Today() Date

Today returns today's date according to the current local time.

func TodayIn

func TodayIn(loc *time.Location) Date

TodayIn returns today's date according to the current time relative to the specified location.

func TodayUTC

func TodayUTC() Date

TodayUTC returns today's date according to the current UTC time.

func (Date) AddDate

func (d Date) AddDate(years, months, days int) Date

AddDate returns the date corresponding to adding the given number of years, months, and days to d. For example, AddData(-1, 2, 3) applied to January 1, 2011 returns March 4, 2010.

AddDate normalizes its result in the same way that Date does, so, for example, adding one month to October 31 yields December 1, the normalized form for November 31.

The addition of all fields is performed before normalisation of any; this can affect the result. For example, adding 0y 1m 3d to September 28 gives October 31 (not November 1).

Example
d := New(1000, time.January, 1)
// Months and days do not need to be constrained to [1,12] and [1,365].
u := d.AddDate(0, 14, -1)
fmt.Println(u)
Output:

1001-02-28

func (Date) AddPeriod

func (d Date) AddPeriod(delta period.Period) Date

AddPeriod returns the date corresponding to adding the given period. If the period's fields are be negative, this results in an earlier date.

Any time component only affects the result for periods containing more that 24 hours in the hours/minutes/seconds fields

func (Date) Date

func (d Date) Date() (year int, month time.Month, day int)

Date returns the year, month, and day of d. The first day of the month is 1.

func (Date) Day

func (d Date) Day() int

Day returns the day of the month specified by d. The first day of the month is 1.

func (Date) Format

func (d Date) Format(layout string) string

Format returns a textual representation of the date value formatted according to layout, which defines the format by showing how the reference date, defined to be

Mon, Jan 2, 2006

would be displayed if it were the value; it serves as an example of the desired output.

This function actually uses time.Format to format the input and can use any layout accepted by time.Format by extending its date to a time at 00:00:00.000 UTC.

Additionally, it is able to insert the day-number suffix into the output string. This is done by including "nd" in the format string, which will become

Mon, Jan 2nd, 2006

For example, New Year's Day might be rendered as "Fri, Jan 1st, 2016". To alter the suffix strings for a different locale, change DaySuffixes or use FormatWithSuffixes instead.

This function cannot currently format Date values according to the expanded year variant of ISO 8601; you should use Date.FormatISO to that effect.

Example
// layout shows by example how the reference time should be represented.
const layout = "Jan 2, 2006"
d := New(2009, time.November, 10)
fmt.Println(d.Format(layout))
Output:

Nov 10, 2009

func (Date) FormatISO

func (d Date) FormatISO(yearDigits int) string

FormatISO returns a textual representation of the date value formatted according to the expanded year variant of the ISO 8601 extended format; the year of the date is represented as a signed integer using the specified number of digits (ignored if less than four). The string representation of the year will take more than the specified number of digits if the magnitude of the year is too large to fit.

Function Date.Format can be used to format Date values in other formats, but it is currently not able to format dates according to the expanded year variant of the ISO 8601 format.

Example
// According to legend, Rome was founded on April 21, 753 BC.
// Note that with astronomical year numbering, 753 BC becomes -752
// because 1 BC is actually year 0.
d := New(-752, time.April, 21)
fmt.Println(d.FormatISO(5))
Output:

-00752-04-21

func (Date) FormatOrdinal

func (d Date) FormatOrdinal() string

FormatOrdinal returns a textual representation of the date value formatted according to the ordinal date variant of the ISO 8601 format. The year of the date is represented as a signed integer. The three-digit ordinal day number is appended.

func (Date) FormatWithSuffixes

func (d Date) FormatWithSuffixes(layout string, suffixes []string) string

FormatWithSuffixes is the same as Format, except the suffix strings can be specified explicitly, which allows multiple locales to be supported. The suffixes slice should contain 31 strings covering the days 1 (index 0) to 31 (index 30).

func (Date) ISOWeek

func (d Date) ISOWeek() (year, week int)

ISOWeek returns the ISO 8601 year and week number in which d occurs. Week ranges from 1 to 53. Jan 01 to Jan 03 of year n might belong to week 52 or 53 of year n-1, and Dec 29 to Dec 31 might belong to week 1 of year n+1.

func (Date) LastDayOfMonth

func (d Date) LastDayOfMonth() int

LastDayOfMonth returns the last day of the month specified by d. The first day of the month is 1.

func (Date) MarshalBinary

func (d Date) MarshalBinary() (b []byte, err error)

MarshalBinary implements the encoding.BinaryMarshaler interface.

func (Date) MarshalText

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

MarshalText implements the encoding.TextMarshaler interface. The date is given in ISO 8601 extended format (e.g. "2006-01-02"). If the year of the date falls outside the [0,9999] range, this format produces an expanded year representation with possibly extra year digits beyond the prescribed four-digit minimum and with a + or - sign prefix (e.g. , "+12345-06-07", "-0987-06-05").

func (Date) Midnight

func (d Date) Midnight() time.Time

Midnight returns a Time value corresponding to midnight on the given date d, local time. Note that midnight is the beginning of the day rather than the end.

func (Date) MidnightIn

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

MidnightIn returns a Time value corresponding to midnight on the given date d, relative to the specified time zone. Note that midnight is the beginning of the day rather than the end.

func (Date) MidnightUTC

func (d Date) MidnightUTC() time.Time

MidnightUTC returns a Time value corresponding to midnight on the given date d, UTC time. Note that midnight is the beginning of the day rather than the end.

func (Date) Month

func (d Date) Month() time.Month

Month returns the month of the year specified by d.

func (*Date) Scan

func (d *Date) Scan(value interface{}) (err error)

Scan parses some value. If the value holds a string, the AutoParse function is used. Otherwise, if the value holds an integer, it is treated as the period of days since year 0 value that represents a Date.

This implements sql.Scanner https://golang.org/pkg/database/sql/#Scanner

func (Date) String

func (d Date) String() string

String returns the time formatted in ISO 8601 extended format (e.g. "2006-01-02"). If the year of the date falls outside the [0,9999] range, this format produces an expanded year representation with possibly extra year digits beyond the prescribed four-digit minimum and with a + or - sign prefix (e.g. , "+12345-06-07", "-0987-06-05").

func (Date) Time

func (d Date) Time(clock clock.Clock, loc *time.Location) time.Time

Time returns a Time value corresponding to a clock time on the given date d, relative to the specified time zone. A common use-case is to obtain the midnight time, for which the clock value is simply zero.

func (*Date) UnmarshalBinary

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

UnmarshalBinary implements the encoding.BinaryUnmarshaler interface.

func (*Date) UnmarshalText

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

UnmarshalText implements the encoding.TextUnmarshaler interface. The date is expected to be in ISO 8601 extended format (e.g. "2006-01-02", "+12345-06-07", "-0987-06-05"); the year must use at least 4 digits and if outside the [0,9999] range must be prefixed with a + or - sign. Note that the a blank string is unmarshalled as the zero value.

func (Date) Value

func (d Date) Value() (driver.Value, error)

Value converts the value for DB storage. It uses Valuer, which returns strings by default.

This implements driver.Valuer https://golang.org/pkg/database/sql/driver/#Valuer

func (Date) Weekday

func (d Date) Weekday() time.Weekday

Weekday returns the day of the week specified by d.

func (Date) WriteTo

func (d Date) WriteTo(w io.Writer) (n64 int64, err error)

WriteTo is as per String, albeit writing to an io.Writer.

func (Date) Year

func (d Date) Year() int

Year returns the year specified by d.

func (Date) YearDay

func (d Date) YearDay() int

YearDay returns the day of the year specified by d, in the range [1,365] for non-leap years, and [1,366] in leap years.

Directories

Path Synopsis
Package clock specifies a time of day with resolution to the nearest millisecond.
Package clock specifies a time of day with resolution to the nearest millisecond.
This tool prints equivalences between the string representation and the internal numerical representation for dates and clocks.
This tool prints equivalences between the string representation and the internal numerical representation for dates and clocks.
Package gregorian provides utility functions for the Gregorian calendar calculations.
Package gregorian provides utility functions for the Gregorian calendar calculations.
Package timespan provides spans of time (TimeSpan), and ranges of dates (DateRange).
Package timespan provides spans of time (TimeSpan), and ranges of dates (DateRange).
Package view provides a simple API for formatting dates as strings in a manner that is easy to use in view-models, especially when using Go templates.
Package view provides a simple API for formatting dates as strings in a manner that is easy to use in view-models, especially when using Go templates.

Jump to

Keyboard shortcuts

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