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.
* `period.Period` which expresses a period corresponding to the ISO-8601 form (e.g. "PT30S").
* `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
Index ¶
- Constants
- Variables
- func DaysIn(year int, month time.Month) int
- func IsLeap(year int) bool
- type Date
- func AutoParse(value string) (Date, error)
- func Max() Date
- func Min() Date
- func MustAutoParse(value string) Date
- func MustParse(layout, value string) Date
- func MustParseISO(value string) Date
- func New(year int, month time.Month, day int) Date
- func NewAt(t time.Time) Date
- func NewOfDays(p PeriodOfDays) Date
- func Parse(layout, value string) (Date, error)
- func ParseISO(value string) (Date, error)
- func Today() Date
- func TodayIn(loc *time.Location) Date
- func TodayUTC() Date
- func (d Date) Add(days PeriodOfDays) Date
- func (d Date) AddDate(years, months, days int) Date
- func (d Date) AddPeriod(delta period.Period) Date
- func (d Date) After(u Date) bool
- func (d Date) Before(u Date) bool
- func (d Date) Date() (year int, month time.Month, day int)
- func (d Date) DateString() DateString
- func (d Date) Day() int
- func (d Date) DaysSinceEpoch() (days PeriodOfDays)
- func (d Date) Equal(u Date) bool
- func (d Date) Format(layout string) string
- func (d Date) FormatISO(yearDigits int) string
- func (d Date) FormatWithSuffixes(layout string, suffixes []string) string
- func (d Date) ISOWeek() (year, week int)
- func (d Date) In(loc *time.Location) time.Time
- func (d Date) IsZero() bool
- func (d Date) LastDayOfMonth() int
- func (d Date) Local() time.Time
- func (d Date) MarshalBinary() ([]byte, error)
- func (d Date) MarshalJSON() ([]byte, error)
- func (d Date) MarshalText() ([]byte, error)
- func (d Date) Max(u Date) Date
- func (d Date) Min(u Date) Date
- func (d Date) Month() time.Month
- func (d *Date) Scan(value interface{}) (err error)
- func (d Date) String() string
- func (d Date) Sub(u Date) (days PeriodOfDays)
- func (d Date) UTC() time.Time
- func (d *Date) UnmarshalBinary(data []byte) error
- func (d *Date) UnmarshalText(data []byte) (err error)
- func (d Date) Value() (driver.Value, error)
- func (d Date) Weekday() time.Weekday
- func (d Date) WriteTo(w io.Writer) (n64 int64, err error)
- func (d Date) Year() int
- func (d Date) YearDay() int
- type DateString
- func (ds DateString) Date() Date
- func (ds DateString) MarshalBinary() ([]byte, error)
- func (ds DateString) MarshalJSON() ([]byte, error)
- func (ds DateString) MarshalText() ([]byte, error)
- func (ds *DateString) Scan(value interface{}) (err error)
- func (ds *DateString) UnmarshalBinary(data []byte) error
- func (ds *DateString) UnmarshalText(data []byte) (err error)
- func (ds DateString) Value() (driver.Value, error)
- type PeriodOfDays
Examples ¶
Constants ¶
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 ¶
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.
var DisableTextStorage = false
Deprecated: DisableTextStorage is no longer used.
Functions ¶
Types ¶
type Date ¶
type Date struct {
// contains filtered or unexported fields
}
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 value requires 4 bytes of storage and can represent dates from Tue, 23 Jun -5,877,641 (5,877,642 BC) to Fri, 11 Jul 5,881,580. Dates outside that range will "wrap around".
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 Before, After, and Equal methods as well as the == and != operators.
The Sub method subtracts two dates, returning the number of days between them. The Add method adds a Date and a number of days, producing a Date.
The zero value of type Date is Thursday, January 1, 1970 (called 'the epoch'), based on Unix convention. The IsZero method gives a simple way of detecting a date that has not been initialized explicitly, with the caveat that this is also a 'normal' date.
The first official date of the Gregorian calendar was Friday, October 15th 1582, quite unrelated to the epoch used here. The Date type does not distinguish between official Gregorian dates and earlier proleptic dates, which can also be represented when needed.
func AutoParse ¶
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 "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)
* surrounding whitespace is ignored
func Max ¶
func Max() Date
Max returns the largest representable date.
Example ¶
d := Max() fmt.Println(d)
Output: +5881580-07-11
func Min ¶
func Min() Date
Min returns the smallest representable date.
Example ¶
d := Min() fmt.Println(d)
Output: -5877641-06-23
func MustAutoParse ¶
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 MustParse ¶
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 ¶
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 ¶
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("The world ends on %s\n", d)
Output: The world ends on 9999-12-31
func NewAt ¶
NewAt returns the Date value corresponding to the given time. Note that the date is computed relative to the time zone specified by the given Time value.
func NewOfDays ¶
func NewOfDays(p PeriodOfDays) Date
NewOfDays returns the Date value corresponding to the given period since the epoch (1st January 1970), which may be negative.
func Parse ¶
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.
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, "Tue, February 3, 2013") fmt.Println(d) // shortForm is another way the reference date would be represented // in the desired layout. const shortForm = "2006-Jan-02" d, _ = Parse(shortForm, "2013-Feb-03") fmt.Println(d)
Output: 2013-02-03 2013-02-03
func ParseISO ¶
ParseISO parses an ISO 8601 formatted string and returns the date value it represents. In addition to the common formats (e.g. 2006-01-02 and 20060102), this function accepts date strings using the 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").
If a time field is present, it is ignored. For example, "2018-02-03T00:00:00Z" is parsed as 3rd February 2018.
Note that ParseISO is a little looser than the ISO 8601 standard and will be happy to parse dates with a year longer in length than the four-digit minimum even if they are missing the + sign prefix.
Function date.Parse can be used to parse date strings in other formats, but it is currently not able to parse ISO 8601 formatted strings that use the expanded year format.
Background: https://en.wikipedia.org/wiki/ISO_8601#Dates
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 TodayIn ¶
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) Add ¶
func (d Date) Add(days PeriodOfDays) Date
Add returns the date d plus the given number of days. The parameter may be negative.
func (Date) AddDate ¶
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 ¶
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 is ignored. Therefore, be careful with periods containing more that 24 hours in the hours/minutes/seconds fields. These will not be normalised for you; if you want this behaviour, call delta.Normalise(false) on the input parameter.
For example, PT24H adds nothing, whereas P1D adds one day as expected. To convert a period such as PT24H to its equivalent P1D, use delta.Normalise(false) as the input.
See the description for AddDate.
func (Date) DateString ¶ added in v1.11.0
func (d Date) DateString() DateString
DateString provides a simple fluent type conversion from the underlying type.
func (Date) DaysSinceEpoch ¶
func (d Date) DaysSinceEpoch() (days PeriodOfDays)
DaysSinceEpoch returns the number of days since the epoch (1st January 1970), which may be negative.
func (Date) Format ¶
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 ¶
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) FormatWithSuffixes ¶
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 ¶
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) In ¶
In returns a Time value corresponding to midnight on the given date, relative to the specified time zone. Note that midnight is the beginning of the day rather than the end.
func (Date) IsZero ¶
IsZero reports whether d represents the zero (i.e. uninitialised) date. Because Date follows Unix conventions, it is based on 1970-01-01. So be careful with this: the corresponding 1970-01-01 date is not itself a 'zero'.
func (Date) LastDayOfMonth ¶
LastDayOfMonth returns the last day of the month specified by d. The first day of the month is 1.
func (Date) Local ¶
Local returns a Time value corresponding to midnight on the given date, local time. Note that midnight is the beginning of the day rather than the end.
func (Date) MarshalBinary ¶
MarshalBinary implements the encoding.BinaryMarshaler interface.
func (Date) MarshalJSON ¶ added in v1.17.0
MarshalJSON implements the json.Marshaler 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"). Note that the zero value is marshalled as a blank string, which allows "omitempty" to work.
func (Date) MarshalText ¶
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) Scan ¶
Scan parses some value. If the value holds an integer, it is treated as the period-of-days value that represents a Date. Otherwise, if it holds a string, the AutoParse function is used.
This implements sql.Scanner https://golang.org/pkg/database/sql/#Scanner
func (Date) 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) Sub ¶
func (d Date) Sub(u Date) (days PeriodOfDays)
Sub returns d-u as the number of days between the two dates.
func (Date) UTC ¶
UTC returns a Time value corresponding to midnight on the given date, UTC time. Note that midnight is the beginning of the day rather than the end.
func (*Date) UnmarshalBinary ¶
UnmarshalBinary implements the encoding.BinaryUnmarshaler interface.
func (*Date) UnmarshalText ¶
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 ¶
Value converts the value to an int64. Note that if you need to store as a string, convert the Date to a DateString.
This implements driver.Valuer https://golang.org/pkg/database/sql/driver/#Valuer
type DateString ¶ added in v1.11.0
type DateString Date
DateString alters Date to make database storage use a string column, or a similar derived column such as SQL DATE. (Otherwise, Date is stored as an integer).
func (DateString) Date ¶ added in v1.11.0
func (ds DateString) Date() Date
Date provides a simple fluent type conversion to the underlying type.
func (DateString) MarshalBinary ¶ added in v1.12.0
func (ds DateString) MarshalBinary() ([]byte, error)
MarshalBinary implements the encoding.BinaryMarshaler interface.
func (DateString) MarshalJSON ¶ added in v1.17.0
func (ds DateString) MarshalJSON() ([]byte, error)
MarshalJSON implements the json.Marshaler 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"). Note that the zero value is marshalled as a blank string, which allows "omitempty" to work.
func (DateString) MarshalText ¶ added in v1.12.0
func (ds DateString) 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 (*DateString) Scan ¶ added in v1.11.0
func (ds *DateString) Scan(value interface{}) (err error)
Scan parses some value. If the value holds an integer, it is treated as the period-of-days value that represents a Date. Otherwise, if it holds a string, the AutoParse function is used.
This implements sql.Scanner https://golang.org/pkg/database/sql/#Scanner
func (*DateString) UnmarshalBinary ¶ added in v1.12.0
func (ds *DateString) UnmarshalBinary(data []byte) error
UnmarshalBinary implements the encoding.BinaryUnmarshaler interface.
func (*DateString) UnmarshalText ¶ added in v1.12.0
func (ds *DateString) 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.
func (DateString) Value ¶ added in v1.11.0
func (ds DateString) Value() (driver.Value, error)
Value converts the value to a string. Note that if you only need to store as an int64, convert the DateString to a Date.
This implements driver.Valuer https://golang.org/pkg/database/sql/driver/#Valuer
type PeriodOfDays ¶
type PeriodOfDays int32
PeriodOfDays describes a period of time measured in whole days. Negative values indicate days earlier than some mark.
const ZeroDays PeriodOfDays = 0
ZeroDays is the named zero value for PeriodOfDays.
func (PeriodOfDays) Date ¶
func (p PeriodOfDays) Date() Date
Date returns the Date value corresponding to the given period since the epoch (1st January 1970), which may be negative.
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 period provides functionality for periods of time using ISO-8601 conventions.
|
Package period provides functionality for periods of time using ISO-8601 conventions. |
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. |