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
Index ¶
- Constants
- Variables
- func ValueAsInt(d Date) (driver.Value, error)
- func ValueAsString(d Date) (driver.Value, error)
- type Date
- func AutoParse(value string) (Date, error)
- func AutoParseUS(value string) (Date, error)
- func Max() Date
- func Min() Date
- func MustAutoParse(value string) Date
- func MustAutoParseUS(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 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) AddDate(years, months, days int) Date
- func (d Date) AddPeriod(delta period.Period) Date
- func (d Date) Date() (year int, month time.Month, day int)
- func (d Date) Day() int
- func (d Date) Format(layout string) string
- func (d Date) FormatISO(yearDigits int) string
- func (d Date) FormatOrdinal() string
- func (d Date) FormatWithSuffixes(layout string, suffixes []string) string
- func (d Date) ISOWeek() (year, week int)
- func (d Date) LastDayOfMonth() int
- func (d Date) MarshalBinary() (b []byte, err error)
- func (d Date) MarshalText() ([]byte, error)
- func (d Date) Midnight() time.Time
- func (d Date) MidnightIn(loc *time.Location) time.Time
- func (d Date) MidnightUTC() time.Time
- func (d Date) Month() time.Month
- func (d *Date) Scan(value interface{}) (err error)
- func (d Date) String() string
- func (d Date) Time(clock clock.Clock, loc *time.Location) 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
Examples ¶
Constants ¶
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 )
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 Valuer = ValueAsString
Valuer is the pluggable implementation function for converting dates to driver.Value. It is initialised with ValueAsString.
Functions ¶
func ValueAsInt ¶
ValueAsInt converts a date for DB storage using an integer.
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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("%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 ¶
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 ¶
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 ¶
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.
If a time field is present, it is ignored. For example, "2018-02-03T00:00:00Z" is parsed as 3rd February 2018.
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 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) 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 only affects the result for periods containing more that 24 hours in the hours/minutes/seconds fields
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) FormatOrdinal ¶
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 ¶
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) LastDayOfMonth ¶
LastDayOfMonth returns the last day of the month specified by d. The first day of the month is 1.
func (Date) MarshalBinary ¶
MarshalBinary implements the encoding.BinaryMarshaler interface.
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) Midnight ¶
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 ¶
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 ¶
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) Scan ¶
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 ¶
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 ¶
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 ¶
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.
func (Date) Value ¶
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
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. |