date

package
v1.0.0-beta.2 Latest Latest
Warning

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

Go to latest
Published: Oct 16, 2026 License: MIT Imports: 17 Imported by: 7 modules, 6 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

date

Calendar dates as ISO 8601 strings (YYYY-MM-DD) that parse the many ways people write dates: "25.12.2023", "Dec 25, 2023", "1. Dezember 2016", "2023-12-25T10:00:00Z". Use Date for required dates, NullableDate for optional ones, and YearMonth / YearQuarter for reporting periods. The types are strings, so they work as map keys, compare cheaply and are readable in logs and SQL.

import "github.com/domonda/go-types/date"

Types

Type Purpose
Date A calendar date, canonical form YYYY-MM-DD. Empty and the zero dates are not valid.
NullableDate Like Date, but Null ("") and the zero dates are valid and SQL NULL.
YearMonth A month, YYYY-MM.
NullableYearMonth YearMonth where "", whitespace and the zero values 0001-01 and 0000-00 are null.
YearQuarter A quarter, YYYY-Qn with an upper-case Q.
NullableYearQuarter YearQuarter where "", whitespace and the zero values 0001-Q1 and 0000-Q0 are null.
Format Layout plus nil and zero placeholders, for reflection based formatting.
Formatter A time layout string that formats and parses dates.
Parser Parses any accepted input to YYYY-MM-DD.
Finder Finds dates in text.

Date

const (
    Layout    = time.DateOnly // "2006-01-02"
    Regex     = `\d{4}-\d{2}-\d{2}`
    Length    = 10 // len("2006-01-02")
    MinLength = 6  // minimum length of a valid date
    Invalid   Date = ""
)

A Date holds whatever string you assign. Methods normalize on demand, so Date("25.12.2023") is valid and behaves like "2023-12-25" in every method except ==. SQL Scan and Value of a string store the canonical form and treat a zero date as blank. JSON, XML and MarshalText trim and also store a zero date as blank. ScanString without validate does the same. A time.Time from the driver is stored with OfTime, or as blank when that date is zero.

A Date is zero, see IsZero, if it is empty, whitespace only, or one of the zero dates "0000-00-00" and "0001-01-01" in any spelling, like "01.01.0001" or Go's zero time "0001-01-01T00:00:00Z". A zero date has no practical use as a date: it is not valid. SQL Scan, JSON and XML store it as "" and Value writes SQL NULL.

Parsing

Normalize(str, lang...), Date.Normalized() and Date.NormalizedLang(lang) accept, case-insensitive and with lenient whitespace:

  • ISO dates with -, /, . or space as separator: "2006-01-02", "2006/01/02".
  • An ISO date followed by a T time ("2006-01-02T15:04:05Z07:00") or a trailing 00:00:00 ("30.11.2023 00:00:00"). The time is dropped.
  • Numeric day-month-year and month-day-year with 2 or 4 digit years: "25.12.1975", "25.12.75", "12/25/1975".
  • English and German month names and abbreviations: "jan. 24 2012", "1. Dezember 2016", "Oct 7, 1970", "September 17th, 2012", "Oct 7, '70", "2013-Feb-03", "07-Feb-04". Common OCR misreadings like "1an" or "apri1" are accepted too.
  • French, Italian and Spanish month names and their usual abbreviations: "2 janv. 2019", "23/gen/2019", "12 enero 2020", "2 févr. 2019", "5 luglio 2021".
  • English ordinals and a leading weekday: "1st of dec. 2020", "Fri, 03 Jul 2015".
  • CJK separators: "2014年04月08日".

Not supported: year-only or year-month strings ("2014", "2014-04"), compact digits ("20140601"), dates whose three parts have fewer than 5 characters together ("8/8/71"), and times with a zone offset inside the string ("Mon Jan 02 15:04:05 -0700 2006"). Use time.Parse or ParseTime for those.

Rules for numeric dates:

  • Separators decide. An ambiguous date with dots is day first like in Germany: "05.06.2024" is 2024-06-05. Other separators are day first too: "05-06-2024" and "05 06 2024" are 2024-06-05, and so is a mix like "05/06.2024", with every language hint. Only slashes are written in both orders, month first in the US and day first in Britain, so only for them the hint decides. Without a hint they are month first like in the US: "05/06/2024" and "05/06/24" are 2024-05-06. SQL Scan and ScanString with validate have no hint and read this way. JSON, XML and ScanString without validate only trim.
  • Language hint for slashes. The first lang argument is a hint, normalized with language.Code.Normalized, so language.EN, "EN", " en", "en-US" and "eng" all mean English. A hint that can't be normalized, like "english", is ignored like no hint. For a date with slashes English reads month first, every other language day first, so "05/06/2024" with language.DE is 2024-06-05. "en-GB" is English too and reads slashes month first. The hint doesn't change other separators: "05.06.2024" with language.EN is 2024-06-05.
  • Only ambiguous dates. The separators and the hint apply only when both numbers are 1 to 12. "15.06.2024", "15/06/2024" and "06/15/2024" all give 2024-06-15 with any hint.
  • Ordinal suffix. A suffix like "1st" marks the day for ambiguous dates and wins over the hint and the separators: "02 1st 2003" and "1st 02 2003" are 2003-02-01, also with language.EN, and "3rd/04/2024" is 2024-04-03. A number with a suffix is never the month, so "13 1st 2024" is an error.
  • Two-digit years. 00 to 44 become 2000 to 2044, 45 to 99 become 1945 to 1999. A single digit is never the year, so "12.12.5" is an error, and the year 0 is an error in every order, like "0000 25 may".
  • Date-times. A T after the date is only cut off with the time if a digit follows, so "2023-12-25T10:00:00Z" is 2023-12-25 and "2023-12-25TOTAL" is an error.
Functions
Function Description
Normalize(str, lang...) Parses str and returns the YYYY-MM-DD form, or an error.
Must(str) Normalize without hint; panics on error.
StringIsDate(str, lang...) Reports whether Normalize accepts str.
Of(year, month, day) Date from parts. Out of range values roll over: October 32 is November 1.
OfTime(t) Date part of t in t's location; "" for the zero time.Time.
OfTimePtr(t) Like OfTime, returns a NullableDate: Null for nil or the zero time.
OfToday(), OfYesterday(), OfTomorrow() In the local time zone.
OfNowInUTC() Today in UTC.
OfTodayIn(loc) Today in loc.
Parse(layout, value) time.Parse, then the date part. Returns "" without error if the time is zero.
Validation and normalization
Method Description
Valid() True if Normalized() succeeds. No hint, so any parseable form is valid.
Validate() The error of Normalized(), or nil.
Normalized() The YYYY-MM-DD form, or the date unchanged and an error, also for a zero date. Implements types.Normalizable[Date], so it has no order hint.
NormalizedLang(lang) Like Normalized, with lang as order hint.
ValidAndNormalized() True only if the date is already a valid YYYY-MM-DD, not a zero date.
NormalizedOrUnchanged(lang...) Normalized form, or the date unchanged if it can't be parsed.
NormalizedOrNull(lang...) Normalized form as NullableDate, or Null.
IsZero() True for an empty or whitespace only date and the zero dates "0000-00-00" and "0001-01-01" in any spelling.
Nullable() Converts to NullableDate; zero dates become Null.
ScanString(source, validate) Without validate trims surrounding whitespace, including a zero date. With validate assigns the normalized source or returns the error of Normalized, also for a blank or zero source.
ScanStringWithLang(source, lang) Assigns the normalized source using the hint lang, "" for a zero date. Returns wasNormalized (source was already YYYY-MM-DD), monthMustBeFirst (only month first is valid, like "12/25/2023") and an error. Unchanged on error.

monthMustBeFirst lets you detect the date order of a whole document from one unambiguous date, then pass language.EN for the rest instead of a day first document language, so that its ambiguous dates with slashes are read month first. Dates with dots, dashes or spaces stay day first with every hint. It is false for an ambiguous date like "05/06/2024", also when that is read month first because of its slashes.

Conversion to time.Time and strings
Method Description
MidnightUTC() 00:00 UTC of the date. Zero time.Time if the date is zero or invalid.
Midnight() 00:00 in time.Local, same rules.
MidnightInLocation(loc) 00:00 in loc, same rules.
Time(hour, minute, second, loc) The date at a time of day. Zero time.Time for a zero date. An invalid date gives a meaningless time before year 1.
TimeLocal(hour, minute, second) Time in time.Local.
TimeUTC(hour, minute, second) Time in UTC.
Format(layout) Formats with a time layout. "" if the date is zero or layout is empty. Format(Layout) returns the normalized date, or an invalid date unchanged.
Parts
Method Description
Year(), Month(), Day() The parts, 0 if invalid.
YearMonthDay() All three parts, zeros if invalid.
Weekday() Day of the week, time.Sunday (0) if zero or invalid.
ISOWeek() ISO 8601 year and week number, zeros if zero or invalid.
Comparison
Method Description
Compare(other) -1, 0 or +1 comparing the normalized strings. Invalid dates compare like "".
NormalizedEqual(other) True if both normalize to the same string. False if either is invalid, even for identical strings.
After(other), Before(other) Strict order of the UTC midnights. False if either date is invalid, also "", like NormalizedEqual.
EqualOrAfter(other), EqualOrBefore(other) Inclusive variants.
WithinIncl(from, until) from <= date <= until. False if any date is invalid.
BetweenExcl(after, before) after < date < before. False if any date is invalid.
AfterTime(t), BeforeTime(t) Compares midnight of the date in t's location with t. False for an invalid date.
IsToday(), IsTodayInUTC() NormalizedEqual(OfToday()) / NormalizedEqual(OfNowInUTC()).
AfterToday(), AfterTodayInUTC(), BeforeToday(), BeforeTodayInUTC() After / Before today in the local time zone or UTC.
Arithmetic and period boundaries
Method Description
AddDate(years, months, days) Like time.Time.AddDate, overflow rolls over: "2024-01-31" + 1 month is "2024-03-02".
AddYears(n), AddMonths(n), AddDays(n) Shortcuts for AddDate.
Add(d) Adds a time.Duration to midnight UTC and returns the date part.
Sub(other) date - other as time.Duration.
BeginningOfWeek(startDay), EndOfWeek(startDay) First and last day of the week that starts on startDay (time.Monday for ISO weeks).
BeginningOfMonth(), EndOfMonth() First and last day of the month.
BeginningOfQuarter(), EndOfQuarter() First and last day of the quarter.
BeginningOfYear(), EndOfYear() January 1 and December 31.
LastMonday() The Monday on or before the date.
NextSunday() The Sunday on or after the date.

Implements: database/sql.Scanner, database/sql/driver.Valuer, json.Marshaler, json.Unmarshaler, encoding.TextMarshaler, xml.Unmarshaler, xml.UnmarshalerAttr, xml.MarshalerAttr, strfmt.Scannable, types.Validator, types.Validatable, types.NormalizableValidator[Date] and JSONSchema() ({"type":"string","format":"date"}). Date has no String method, so fmt prints the stored date, and no UnmarshalText, so encoding/json reads the keys of a map[Date]V as given.

NullableDate

const Null NullableDate = ""

NullableDate has the same string form as Date. Null, a value of only the runes strutil.TrimSpace removes (like for country.NullableCode), the zero dates "0000-00-00" and "0001-01-01", and a zero date in another format like "01.01.0001" are null, valid, and written as SQL NULL and JSON null.

Function Description
NormalizeNullable(str, lang...) Like Normalize; Null without error for "" and zero dates.
MustNullable(str) NormalizeNullable without hint; panics on error.
OfTimePtr(t) See Date functions.
Method Description
IsNull() True for Null, only strutil.TrimSpace runes and the zero dates, also in another format like "01.01.0001".
IsZero() True for Null and the zero dates.
IsNotNull() !IsNull().
Get() The Date; panics if null.
GetOr(defaultDate), DateOr(useIfNull) The Date, or the argument if null.
Date() Plain conversion to Date, no null check.
Set(d), SetNull() Assign a Date or Null.
Valid(), Validate() Null is valid, otherwise like Date.
ValidAndNotNull() Valid and not null, so false for the zero dates.
ValidAndNormalized() True for Null and for a valid YYYY-MM-DD that is not a zero date.
Normalized(), NormalizedLang(lang) Null for null input, otherwise like Date.
NormalizedOrNull(lang...), NormalizedOrUnchanged(lang...) As for Date.
StringOr(nullString) As stored, or nullString if null.
ScanString(source, validate) "", "NULL", "null", "nil" and whitespace only set Null; otherwise like Date.
ScanStringWithLang(source, lang) A null source sets Null; otherwise like Date.
MidnightUTC(), Midnight(), MidnightInLocation(loc) Return nullable.Time, null for null or invalid dates.

These methods mirror Date and add null rules:

Methods Null rule
AddDate, AddYears, AddMonths, AddDays, Add, BeginningOf*, EndOf*, LastMonday, NextSunday Return NullableDate; Null stays Null.
Year, Month, Day, YearMonthDay, Weekday, ISOWeek Zeros for null.
Format(layout) "" for Null.
Compare, NormalizedEqual, After, Before, EqualOrAfter, EqualOrBefore Null is before every valid non-null date. An invalid date is neither before nor after any date, also not Null, but Compare sorts it like Null.
AfterTime(t) False for null and invalid dates. True for a valid non-null date if t is zero.
BeforeTime(t) For null: true unless t is zero. False for an invalid date.
Sub(other) 0 if either is null.
IsToday, IsTodayInUTC, AfterToday, AfterTodayInUTC False for null.
BeforeToday, BeforeTodayInUTC True for null.

NullableDate has no Time, TimeLocal, TimeUTC, WithinIncl, BetweenExcl or Nullable.

Implements: database/sql.Scanner, database/sql/driver.Valuer, json.Marshaler, json.Unmarshaler, encoding.TextMarshaler, xml.Unmarshaler, xml.UnmarshalerAttr, xml.MarshalerAttr, strfmt.Scannable, types.NormalizableValidator[NullableDate], nullable.NullSetable[Date] and JSONSchema() (string with format date, or null). No String method, fmt prints the stored date.

Periods

Function Description
PeriodRange(period) First and last day of "YYYY", "YYYY-MM", "YYYY-Qn", "YYYY-Hn" (half year) or "YYYY-Wnn" (ISO week). The letters may be lower case.
YearRange(year) "YYYY-01-01" and "YYYY-12-31".
YearWeekMonday(year, week) Monday of an ISO 8601 week.
YearWeekRange(year, week) Monday and Sunday of an ISO 8601 week.
FromUntilFromYearAndMonths(year, months) First and last day of a month range: ("2024", "3-9") gives 2024-03-01 and 2024-09-30. Empty months means "1-12"; empty year returns empty dates and no error.

An ISO week runs Monday to Sunday and can start or end in the neighbouring year: PeriodRange("2021-W01") is 2021-01-04 to 2021-01-10, PeriodRange("2019-W01") is 2018-12-31 to 2019-01-06. Week 53 is only accepted for years that have 53 ISO weeks: PeriodRange("2020-W53") is 2020-12-28 to 2021-01-03, PeriodRange("2021-W53") is an error.

YearMonth and NullableYearMonth

const YearMonthLayout = "2006-01"
const YearMonthNull NullableYearMonth = ""
Function Description
YearMonthFrom(year, month) Formats as YYYY-MM without validation.
YearMonthOfTime(t) Year and month of t; "" for the zero time.
YearMonthOfToday() In the local time zone.
YearMonth method Description
Normalized() Trims the surrounding whitespace; the value unchanged and an error if invalid or zero.
Validate(), Valid() Normalized succeeds: YYYY-MM, year 1 to 9999 like Date, month 1 to 12, not zero.
ValidAndNormalized() Exactly YYYY-MM and valid.
IsZero() True for "", "0000-00" and "0001-01", also with whitespace.
String() The raw string.
Year(), Month() The parts, 0 if invalid.
Date(day) "YYYY-MM-DD" for day, without validation (Date(30) of February is invalid).
DateRange() First and last day of the month; "", "" if invalid.
Format(layout) "" if empty; YearMonthLayout returns the normalized value, an invalid one as is; other layouts format the 1st of the month.
AddYears(n), AddMonths(n) Arithmetic; months roll over into years. Invalid values are returned unchanged. A result outside the years 1 to 9999, like "10000-01", is invalid.
ContainsTime(t), ContainsDate(d) True if t or d falls in the month (local time zone midnights).
Compare(other) Compares the normalized values, invalid ones as stored.
Nullable() Plain conversion to NullableYearMonth.

YearMonth trims on every path, including SQL, and keeps a zero period such as "0001-01". See Serialization.

NullableYearMonth has the same methods (null returns 0, "", false or null; Normalized returns YearMonthNull for null) plus IsNull() (the same as IsZero(), like for NullableDate), IsNotNull(), ValidAndNotNull(), Get() (panics if null), GetOr(defaultYearMonth), Set(ym), SetNull() and StringOr(nullString). Its Date and DateRange return NullableDate. Implements nullable.NullSetable[YearMonth] and types.NormalizableValidator. Reading and writing trim and keep "0001-01"; only a blank value is SQL NULL or JSON null.

YearQuarter and NullableYearQuarter

const YearQuarterNull NullableYearQuarter = ""
Function Description
YearQuarterFrom(year, quarter) Formats as YYYY-Qn without validation.
YearQuarterOfTime(t) Quarter of t; "" for the zero time.
YearQuarterOfToday() In the local time zone.
YearQuarter method Description
Normalized() Trims the surrounding whitespace and upper-cases q; the value unchanged and an error if invalid or zero.
Validate(), Valid() Normalized succeeds: YYYY-Qn, year 1 to 9999 like Date, quarter 1 to 4, not zero.
ValidAndNormalized() Exactly YYYY-Qn with upper-case Q and valid.
IsZero() True for "", "0000-Q0" and "0001-Q1", also with whitespace or q.
String() The raw string.
Year(), Quarter() The parts, 0 if invalid.
FirstMonth() January, April, July or October; 0 if invalid.
Date(monthInQuarter, day) Date in the quarter via Of, so values roll over; "" if invalid.
DateRange() First and last day of the quarter; "", "" if invalid.
AddYears(n), AddQuarters(n) Arithmetic; quarters roll over into years. Invalid values are returned unchanged. A result outside the years 1 to 9999, like "10000-Q1", is invalid.
ContainsTime(t), ContainsDate(d), ContainsYearMonth(ym) True if the value falls in the quarter.
Compare(other) Compares the normalized values, invalid ones as stored.
Nullable() Plain conversion to NullableYearQuarter.

YearQuarter trims and uppercases on every path, including SQL, and keeps a zero period such as "0001-Q1". See Serialization.

NullableYearQuarter has the same methods plus the same null helpers as NullableYearMonth. Its Date and DateRange return NullableDate. Implements nullable.NullSetable[YearQuarter] and types.NormalizableValidator. Reading and writing trim and uppercase, and keep "0001-Q1"; only a blank value is SQL NULL or JSON null.

Format, Formatter and Parser

These plug dates into the strfmt package, which calls Parse(str string, langHints ...language.Code) (normalized string, err error).

Type / method Description
Parser{}.Parse(str, langHints...) Normalize, returns YYYY-MM-DD.
Formatter(layout).Format(d) d.Format(layout).
Formatter(layout).Parse(str, langHints...) Normalize, then formats with the layout.
Format{Layout, NilString, ZeroString} Struct with JSON tags layout, nilString, zeroString.
(*Format).Format(d) d.Format(f.Layout).
(*Format).Parse(str, langHints...) Normalize, then formats with Layout. Pointer receiver: only *Format implements strfmt.Parser.
(*Format).AssignString(dest, source) Parses source (with Normalize if Layout is empty, else time.Parse(Layout)) and assigns it to the addressable dest of type Date, NullableDate, time.Time, *time.Time or nullable.Time. Whitespace-only source assigns the empty value. A parsed zero time is an error.
(*Format).FormatString(val) NilString for an invalid reflect.Value or a nil pointer, ZeroString for zero values with Format/IsZero methods (Date, NullableDate, time.Time), else Format(Layout), which returns an invalid date like "bad" unchanged. Other types are an error.

Parser and Formatter implement strfmt.Parser as values, Format only as *Format. None of them implements strfmt.Formatter.

Finder

Identifier Description
NewFinder(lang...) Returns a *Finder with the normalized first lang as hint, no hint if it can't be normalized.
Finder.LangHint The language hint field.
(*Finder).FindAllIndex(str, n) [start, end) byte offsets of dates in str. At most n results; n < 0 returns all, n == 0 none.

*Finder implements types.Finder. It tries spans of one to three whitespace-separated words and trims surrounding punctuation, so "25.12.2023," is found as "25.12.2023". It reports the shortest span that parses at each start word. A span is found exactly if Normalize accepts it, so an ISO 8601 date-time like "2023-12-25T10:00:00Z" is found as a whole. The exception are the Italian and Spanish month abbreviations that are common words in other languages, set, ago, mag, lug, ott and dic: they need language.IT or language.ES as hint, so that "Game set 10 2020" has no date.

time.Time helpers

Identifier Description
ParseTime(str, layouts...) Tries time.Parse with each layout and returns the first success. Defaults to ParseTimeDefaultLayouts.
ParseTimeDefaultLayouts time.RFC3339Nano, time.RFC3339, "2006-01-02 15:04:05". A package variable.

Serialization

Date and NullableDate fully normalize on SQL Scan and Value, with the zero dates as blank. A time.Time is stored with OfTime. JSON and XML only trim. YearMonth only trims on every path, and YearQuarter also uppercases. Their zero values are kept. fmt prints the stored text.

Value SQL Value() JSON (json.Marshal) MarshalText, XML fmt
Date(""), Date(" ") NULL "" "" as stored
Date("0001-01-01"), Date("01.01.0001") NULL "" "" as stored
Date("25.12.2023") (valid, not normalized) "2023-12-25" "25.12.2023" 25.12.2023 25.12.2023
Date("2023-12-25") "2023-12-25" "2023-12-25" 2023-12-25 2023-12-25
Date("bad") (invalid) error of Normalized "bad" bad bad
NullableDate null NULL null "" as stored
NullableDate("0001-01-01") NULL null "" 0001-01-01
NullableDate("25.12.2023") "2023-12-25" "25.12.2023" 25.12.2023 25.12.2023
NullableDate("bad") error of Normalized "bad" bad bad
YearMonth(" 2023-07 "), YearQuarter("2023-q3") "2023-07", "2023-Q3" "2023-07", "2023-Q3" 2023-07, 2023-Q3 as stored
YearMonth("0001-01"), YearQuarter("0001-q1") "0001-01", "0001-Q1" "0001-01", "0001-Q1" 0001-01, 0001-Q1 as stored
YearMonth(""), YearQuarter(" ") NULL "" "" as stored
YearMonth("2023-13") (invalid) "2023-13" "2023-13" 2023-13 2023-13
NullableYearMonth(""), NullableYearQuarter(" ") NULL null "" as stored
NullableYearMonth("0001-01") "0001-01" "0001-01" 0001-01 0001-01

Reading values:

Input Date NullableDate
Scan(nil) "" Null
SQL Scan of a string or []byte normalized if valid, "" if blank or a zero date, else as is, without error same, Null if blank or a zero date
JSON string, XML element or attribute trimmed, including a zero date trimmed, Null only if blank
Scan(time.Time) OfTime, "" if the time is zero its date, Null if the time is zero
Scan(time.Time) into a YearMonth, YearQuarter YearMonthOfTime or YearQuarterOfTime, "" if zero same, null if the time is zero
Scan of other types error error
JSON null field left unchanged Null
other JSON values error error

An invalid date is read without error, so one bad row doesn't fail a whole query, and kept for Validate to report. YearMonth and YearQuarter trim (and a quarter uppercases) on SQL as well as JSON and XML, and they keep a zero period.

Gotchas

  • Valid, Validate, Normalized, ValidAndNormalized. Valid and Validate accept any parseable form: Date("25.12.2023").Valid() is true. Normalized returns the canonical form. ValidAndNormalized is true only for an exact YYYY-MM-DD. Date("") is invalid, NullableDate("") is valid.
  • == compares raw strings. Date("25.12.2023") != Date("2023-12-25"). Use NormalizedEqual or Compare, or normalize on input. A string read with SQL Scan is canonical. JSON and XML only trim.
  • Zero dates are no dates. "0001-01-01" and "0000-00-00", also in another spelling like "01.01.0001", are IsZero() and not valid. SQL Scan, JSON and XML store them as "" and Value writes SQL NULL. Comparisons treat them like an invalid date. YearMonth("0001-01") and YearQuarter("0001-Q1") are kept on every path, and they are not null.
  • Slashes month first, dots day first. Without a hint "05/06/2024" is May 6 and "05.06.2024" is June 5, other separators are day first. A hint only decides slashes: English month first, every other language day first. Dots, dashes and spaces are day first with every hint, so an ambiguous US date written "05-06-2024" is read as June 5 also with language.EN. Neither changes a date that has only one valid reading. Only the first lang argument is used.
  • Two-digit years pivot at 45: "25.12.44" is 2044-12-25, "25.12.45" is 1945-12-25.
  • Invalid and zero dates become the zero time in arithmetic. Date("").AddDays(1) and Date("bad").AddDays(1) return "0001-01-02". Check Valid (or IsZero) before doing arithmetic. Format returns an invalid date unchanged with every layout: Date("bad").Format("02.01.2006") is "bad". Comparisons don't use the zero time: After, Before, WithinIncl, BetweenExcl, AfterTime and BeforeTime are false for an invalid date, so Date("bad").Before("2024-01-01") and Date("2024-01-01").EqualOrAfter("bad") are false.
  • Reading doesn't validate. SQL Scan stores a valid date as YYYY-MM-DD and an invalid one as is, without an error. JSON and XML only trim. An invalid date is an error for Value and written unchanged by MarshalJSON. YearMonth and YearQuarter write an invalid period after prettification, without an error.
  • fmt prints the stored date. fmt.Println(date.Date("25.12.2023")) prints 25.12.2023. MarshalText only trims. Use Format(date.Layout) or Normalized() for YYYY-MM-DD.
  • Null ordering. Null is before every date: Null.Before(d) and d.After(Null) are true, Null.BeforeToday() is true.
  • Format.AssignString with empty input assigns a non-nil pointer to the zero time to a *time.Time destination, not nil.
  • ParseTimeDefaultLayouts is a shared package variable. Pass layouts to ParseTime instead of changing it.

Examples

Parse dates in different formats:

package main

import (
	"fmt"

	"github.com/domonda/go-types/date"
	"github.com/domonda/go-types/language"
)

func main() {
	for _, s := range []string{"25.12.2023", "Dec 25, 2023", "1. Dezember 2016", "2023-12-25T10:00:00Z"} {
		d, err := date.Normalize(s)
		fmt.Println(d, err)
	}

	// Both orders are valid: dots are day first with every hint, slashes
	// month first without a hint, else the hint decides, English month first
	fmt.Println(date.Normalize("05/06/2024"))
	fmt.Println(date.Normalize("05.06.2024"))
	fmt.Println(date.Normalize("05/06/2024", language.DE))
	fmt.Println(date.Normalize("05.06.2024", language.EN))

	// Only one order is valid, so the hint changes nothing
	fmt.Println(date.Normalize("15.06.2024", language.EN))

	// Output:
	// 2023-12-25 <nil>
	// 2023-12-25 <nil>
	// 2016-12-01 <nil>
	// 2023-12-25 <nil>
	// 2024-05-06 <nil>
	// 2024-06-05 <nil>
	// 2024-06-05 <nil>
	// 2024-06-05 <nil>
	// 2024-06-15 <nil>
}

Reporting periods:

package main

import (
	"fmt"

	"github.com/domonda/go-types/date"
)

func main() {
	from, until, err := date.PeriodRange("2024-Q1")
	fmt.Println(from, until, err)

	// ISO week 1 of 2021 starts on Monday, January 4th
	from, until, _ = date.PeriodRange("2021-W01")
	fmt.Println(from, until)

	fmt.Println(date.YearMonth("2024-02").DateRange())

	d := date.Date("10.02.2024")
	fmt.Println(d.BeginningOfQuarter(), d.EndOfMonth(), d.AddMonths(1))

	// Output:
	// 2024-01-01 2024-03-31 <nil>
	// 2021-01-04 2021-01-10
	// 2024-02-01 2024-02-29
	// 2024-01-01 2024-02-29 2024-03-10
}

Optional dates in JSON and SQL, and finding dates in text:

package main

import (
	"encoding/json"
	"fmt"

	"github.com/domonda/go-types/date"
	"github.com/domonda/go-types/language"
)

type Invoice struct {
	Issued date.Date         `json:"issued"`
	Paid   date.NullableDate `json:"paid"`
}

func main() {
	b, _ := json.Marshal(Invoice{Issued: "2024-03-01", Paid: "15.3.2024"})
	fmt.Println(string(b))

	v, _ := date.Null.Value()
	fmt.Println(v)
	v, _ = date.Date("01.03.2024").Value()
	fmt.Println(v)

	text := []byte("Rechnung vom 25.12.2023, fällig am 8. Jänner 2024")
	for _, idx := range date.NewFinder(language.DE).FindAllIndex(text, -1) {
		fmt.Println(string(text[idx[0]:idx[1]]))
	}

	// Output:
	// {"issued":"2024-03-01","paid":"2024-03-15"}
	// <nil>
	// 2024-03-01
	// 25.12.2023
	// 8. Jänner 2024
}

Documentation

Overview

Package date provides calendar dates as ISO 8601 strings (YYYY-MM-DD) with lenient parsing of the many ways people write dates.

Normalize and Date.Normalized turn input like "25.12.2023", "Dec 25, 2023" or "1. Dezember 2016" into "2023-12-25". A numeric date like "05/06/2024", where both orders are valid and no ordinal suffix like "1st" marks the day, is read by its separators: day first with dots like in Germany ("05.06.2024") and with any other separator but slashes, also with an English language hint. Slashes are written in both orders, so for them a language hint decides: English (language.EN, "en-US") reads month first, every other language day first. Without a hint slashes are read month first like in the US. SQL Scan and Value read them that way, because they fully normalize and have no hint. JSON and XML only trim surrounding whitespace, so a slash date stays as written. Two-digit years below 45 are read as 20xx, all others as 19xx.

The package includes:

Methods other than reading and writing normalize their input, so a valid but non-normalized Date like "25.12.2023" works everywhere except in == comparisons. SQL Scan stores a valid date normalized and a zero date like "0001-01-01" as empty, and Value writes the normalized date, SQL NULL for an empty or zero date, and returns an error for an invalid date. JSON and XML only trim surrounding whitespace, so "25.12.2023" and a zero date stay as written. fmt prints a date as stored.

See the README.md of this package for the full API, the serialization rules and the gotchas.

Index

Constants

View Source
const (
	// Layout used for the Date type, compatible with time.Time.Format()
	Layout = time.DateOnly

	// Regular expression for the Layout
	Regex = `\d{4}-\d{2}-\d{2}`

	Length = 10 // len("2006-01-02")

	// MinLength is the minimum length of a valid date
	MinLength = 6

	// Invalid holds an empty string Date.
	// See NullableDate for where an empty string is a valid value.
	Invalid Date = ""
)
View Source
const YearMonthLayout = "2006-01"

YearMonthLayout is the layout string for formatting YearMonth values (YYYY-MM). Compatible with time.Time.Format().

Variables

View Source
var ParseTimeDefaultLayouts = []string{
	time.RFC3339Nano,
	time.RFC3339,
	"2006-01-02 15:04:05",
}

ParseTimeDefaultLayouts contains the default time layouts used for parsing.

Functions

func ParseTime

func ParseTime(str string, layouts ...string) (time.Time, error)

ParseTime is a non-Date related helper function that parses the passed string as time.Time. It uses time.Parse with the passed layouts and returns the first valid parsed time. If no layouts are passed, then ParseTimeDefaultLayouts will be used.

func StringIsDate

func StringIsDate(str string, lang ...language.Code) bool

StringIsDate returns if a string can be parsed as Date. The first given lang argument is used as language hint for parsing.

Types

type Date

type Date string

Date represents a calendar date in ISO 8601 format (YYYY-MM-DD). See NullableDate for a nullable version of this type.

A Date is zero, see IsZero, if it is empty, whitespace only, or one of the zero dates "0000-00-00" and "0001-01-01" in any spelling, which have no practical use as a date. A zero Date is not valid.

Scan and Value fully normalize, because a database date is not free text: a valid date is stored as YYYY-MM-DD, a zero date (see IsZero) is "", Value writes SQL NULL for a zero date and returns an error for a date that can't be normalized, and a time.Time from the driver is its date. JSON, XML, MarshalText and ScanString without validate only trim surrounding whitespace, including a zero date, and do not parse another spelling into YYYY-MM-DD. ScanString with validate stores the normalized date or returns the error of Normalized. fmt prints the date as stored. Date has no UnmarshalText, so encoding/json reads and writes the keys of a map[Date]V as given. See "Reading and writing values" in the README of the module.

func FromUntilFromYearAndMonths

func FromUntilFromYearAndMonths(year, months string) (fromDate, untilDate Date, err error)

FromUntilFromYearAndMonths returns the first and last date of a month range within a given year. The year argument must be a 4-digit year string (e.g. "2024"). The months argument is either a single month number ("3") or a dash-separated range ("3-9"); an empty months string defaults to the full year ("1-12"). Returns empty dates without an error when year is empty.

func Must

func Must(str string) Date

Must returns str as normalized Date or panics if str is not a valid Date.

func Normalize

func Normalize(str string, lang ...language.Code) (Date, error)

Normalize returns str as a Date in the canonical YYYY-MM-DD form, or an error if the input cannot be parsed.

A numeric date with the year last is ambiguous when both of its first numbers are valid months, like "05/06/2024". The separators decide: dots are read day first like in Germany, "05.06.2024" is 2024-06-05, and so are other separators, like "05-06-2024", with any language hint. Slashes are written month first in the US and day first in Britain, so for slashes the first lang argument, if present, is a hint: language.EN reads month first, every other language day first, so "05/06/2024" with language.DE is 2024-06-05. Without a hint slashes are read month first like in the US, "05/06/2024" is 2024-05-06. An English ordinal suffix marks the day and wins over the separators and the hint: "1st 02 2003" is 2003-02-01 also with language.EN.

Accepted input shapes (case-insensitive, lenient whitespace):

  • ISO 8601: "2006-01-02", "2006/01/02", "2006.01.02", "2006 01 02"
  • ISO 8601 with time suffix, the date part is taken: "2006-01-02T15:04:05Z07:00", "30.11.2023 00:00:00"
  • dd.mm.yyyy / dd.mm.yy: "25.12.1975", "25.12.75"
  • mm/dd/yyyy / mm/dd/yy: "12/25/1975", "12/25/75"
  • "1st of 02/2003", "4th of dec. 2020"
  • Month-first English / German: "jan. 24 2012", "1. Dezember 2016"
  • Day-first English / German: "7 oct 1970", "1st of dec. 2020"
  • Month-first with comma: "Oct 7, 1970", "May 17, 2012", "September 17th, 2012"
  • Short year with leading apostrophe: "Oct 7, '70"
  • "yyyy-Mon-dd": "2013-Feb-03"
  • "dd-Mon-yyyy" / "dd-Mon-yy": "07-Feb-2004", "07-Feb-04"
  • With weekday prefix (dropped): "Mon Jan 02 2006", "Fri, 03 Jul 2015", "Wednesday, 28 Feb 2018"
  • CJK separators: "2014年04月08日"
  • French, Italian and Spanish month names and abbreviations: "2 janv. 2019", "23/gen/2019", "12 enero 2020", "2 févr. 2019"

2-digit years map to 2000..2044 (< 45) or 1900..1999 (>= 45).

Explicitly NOT supported (use a different parser, e.g. time.Parse):

  • Year-only or year-month-only strings ("2014", "201412", "20140601", "2014-04", "2014.05")
  • Single-digit day-month-year combinations under 5 total digits ("8/8/71") — too ambiguous to disambiguate reliably
  • RubyDate / RFC1123 with embedded time and timezone offset ("Mon Jan 02 15:04:05 -0700 2006")
  • Locale-specific written forms beyond the abbreviations above (e.g. Arabic numerals, full Russian months)

func Of

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

Of returns a normalized Date for the given year, month, and day. The month, day values may be outside their usual ranges and will be normalized during the conversion. For example, October 32 converts to November 1.

func OfNowInUTC

func OfNowInUTC() Date

OfNowInUTC returns the date of the current time in the UTC timezone.

func OfTime

func OfTime(t time.Time) Date

OfTime returns the date part of the passed time.Time or an empty string if t.IsZero(). To get the date in a certain time zone, pass the time.Time with a location set to the time zone.

func OfToday

func OfToday() Date

OfToday returns the date of today in the local timezone.

func OfTodayIn

func OfTodayIn(loc *time.Location) Date

OfTodayIn returns the date of today in the timezone of the passed location.

func OfTomorrow

func OfTomorrow() Date

OfTomorrow returns the date of tomorrow in the local timezone.

func OfYesterday

func OfYesterday() Date

OfYesterday returns the date of yesterday in the local timezone.

func Parse

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

Parse returns the date part from time.Parse(layout, value).

func PeriodRange

func PeriodRange(period string) (from, until Date, err error)

PeriodRange returns the dates [from, until] for a period defined in one of the following formats:

  • period of a ISO 8601 week of a year: YYYY-Wnn
  • period of a month of a year: YYYY-MM
  • period of a quarter of a year: YYYY-Qn
  • period of a half year: YYYY-Hn
  • period of full year: YYYY

The returned from Date is the first day of the period, the returned until Date is the last day of the period. For a week these are the Monday and the Sunday of the ISO 8601 week, which can fall into the previous or next year.

Examples:

  • Period of June 2018: PeriodRange("2018-06") == Date("2018-06-01"), Date("2018-06-30"), nil
  • Period of Q3 2018: PeriodRange("2018-Q3") == Date("2018-07-01"), Date("2018-09-30"), nil
  • Period of second half of 2018: PeriodRange("2018-H2") == Date("2018-07-01"), Date("2018-12-31"), nil
  • Period of year 2018: PeriodRange("2018") == Date("2018-01-01"), Date("2018-12-31"), nil
  • Period of week 1 2019: PeriodRange("2019-W01") == Date("2018-12-31"), Date("2019-01-06"), nil

func YearRange

func YearRange(year int) (from, until Date)

YearRange returns the date range from first of January to 31st of December of a year.

func YearWeekMonday

func YearWeekMonday(year, week int) (monday Date)

YearWeekMonday returns the date of Monday of an ISO 8601 week.

func YearWeekRange

func YearWeekRange(year, week int) (monday, sunday Date)

YearWeekRange returns the dates of Monday and Sunday of an ISO 8601 week.

func (Date) Add

func (date Date) Add(d time.Duration) Date

Add returns a new date with the specified duration added.

func (Date) AddDate

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

AddDate returns a new date with the specified years, months, and days added. The month and day values may be outside their usual ranges and will be normalized.

func (Date) AddDays

func (date Date) AddDays(days int) Date

AddDays returns a new date with the specified number of days added.

func (Date) AddMonths

func (date Date) AddMonths(months int) Date

AddMonths returns a new date with the specified number of months added.

func (Date) AddYears

func (date Date) AddYears(years int) Date

AddYears returns a new date with the specified number of years added.

func (Date) After

func (date Date) After(other Date) bool

After returns true if the date is after the other date. An invalid date (including "") has no position in time, so After returns false if either date is not valid, like NormalizedEqual returns false for an invalid date.

func (Date) AfterTime

func (date Date) AfterTime(other time.Time) bool

AfterTime returns true if midnight of the date (in the location of the passed time) is after the time. Returns false if the date is not valid, see After.

func (Date) AfterToday

func (date Date) AfterToday() bool

AfterToday returns true if the date is after today in local time.

func (Date) AfterTodayInUTC

func (date Date) AfterTodayInUTC() bool

AfterTodayInUTC returns true if the date is after today in UTC time.

func (Date) Before

func (date Date) Before(other Date) bool

Before returns true if the date is before the other date. Returns false if either date is not valid, see After.

func (Date) BeforeTime

func (date Date) BeforeTime(other time.Time) bool

BeforeTime returns true if midnight of the date (in the location of the passed time) is before the time. Returns false if the date is not valid, see After.

func (Date) BeforeToday

func (date Date) BeforeToday() bool

BeforeToday returns true if the date is before today in local time.

func (Date) BeforeTodayInUTC

func (date Date) BeforeTodayInUTC() bool

BeforeTodayInUTC returns true if the date is before today in UTC time.

func (Date) BeginningOfMonth

func (date Date) BeginningOfMonth() Date

BeginningOfMonth returns the date of the first day of the month containing this date.

func (Date) BeginningOfQuarter

func (date Date) BeginningOfQuarter() Date

BeginningOfQuarter returns the date of the first day of the quarter containing this date.

func (Date) BeginningOfWeek

func (date Date) BeginningOfWeek(startDay time.Weekday) Date

BeginningOfWeek returns the date of the first day of the week containing this date. The startDay parameter specifies which day is considered the start of the week. For example, time.Monday for ISO 8601 weeks, or time.Sunday for US-style weeks.

func (Date) BeginningOfYear

func (date Date) BeginningOfYear() Date

BeginningOfYear returns the date of the first day of the year containing this date.

func (Date) BetweenExcl

func (date Date) BetweenExcl(after, before Date) bool

BetweenExcl returns true if the date is strictly between (exclusive) after and before. Returns false if any of the dates is not valid, see After.

func (Date) Compare

func (date Date) Compare(other Date) int

Compare compares the date with another Date. Returns -1 if date is before other, +1 if after, 0 if equal. An invalid date compares like the empty string: equal to any other invalid date and before every valid date, so Compare is a consistent sort order for slices.SortFunc also for invalid dates.

func (Date) Day

func (date Date) Day() int

Day returns the day of the month component of the date. Returns 0 if the date is not valid.

func (Date) EndOfMonth

func (date Date) EndOfMonth() Date

EndOfMonth returns the date of the last day of the month containing this date.

func (Date) EndOfQuarter

func (date Date) EndOfQuarter() Date

EndOfQuarter returns the date of the last day of the quarter containing this date.

func (Date) EndOfWeek

func (date Date) EndOfWeek(weekday time.Weekday) Date

EndOfWeek returns the date of the last day of the week containing this date. The weekday parameter specifies which day is considered the start of the week. The end of the week is calculated as 6 days after the beginning. For example, if weekday is time.Monday, the end will be Sunday.

func (Date) EndOfYear

func (date Date) EndOfYear() Date

EndOfYear returns the date of the last day of the year containing this date.

func (Date) EqualOrAfter

func (date Date) EqualOrAfter(other Date) bool

EqualOrAfter returns true if the date is equal to or after the other date.

func (Date) EqualOrBefore

func (date Date) EqualOrBefore(other Date) bool

EqualOrBefore returns true if the date is equal to or before the other date.

func (Date) Format

func (date Date) Format(layout string) string

Format formats the date using the given layout string (see time.Time.Format). Returns an empty string if the date is zero (see IsZero) or layout is empty. If layout equals Layout constant, returns the normalized date without a time conversion. A date that is not valid is returned unchanged for every layout instead of formatting the zero time.Time like "01.01.0001".

func (Date) ISOWeek

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

ISOWeek returns the ISO 8601 year and week number in which the date 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. Returns zeros if the date is not valid.

func (Date) IsToday

func (date Date) IsToday() bool

IsToday returns true if the date is today in local time. A valid date that is not in the normalized form is normalized first.

func (Date) IsTodayInUTC

func (date Date) IsTodayInUTC() bool

IsTodayInUTC returns true if the date is today in UTC time. A valid date that is not in the normalized form is normalized first.

func (Date) IsZero

func (date Date) IsZero() bool

IsZero returns true if the date is empty or whitespace only, or one of the zero dates "0000-00-00" and "0001-01-01" in any spelling, like "01.01.0001", "0001-01-01T00:00:00Z", "00.00.0000" or "0000-00-00 00:00:00". "0001-01-01" is the zero value of time.Time, "0000-00-00" may be the zero value of other date implementations, like MySQL. A zero date has no practical use as a date and is not a valid Date. SQL Scan, JSON and XML store it as "" and Value writes SQL NULL. A time.Time on that calendar day is stored as "" too.

func (Date) JSONSchema

func (Date) JSONSchema() *jsonschema.Schema

JSONSchema returns the JSON schema definition for the Date type. Implements the jsonschema.JSONSchemaProvider interface.

func (Date) LastMonday

func (date Date) LastMonday() Date

LastMonday returns the date of the Monday on or before this date.

func (Date) MarshalJSON

func (date Date) MarshalJSON() ([]byte, error)

MarshalJSON implements encoding/json.Marshaler by writing the date with surrounding whitespace trimmed. A zero date is written as "", like Value writes SQL NULL. A blank date is "".

func (Date) MarshalText

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

MarshalText implements encoding.TextMarshaler like MarshalJSON, so that encoding/xml and strfmt write the trimmed date. encoding/json writes map keys of string types as they are and doesn't call MarshalText for them.

func (*Date) MarshalXMLAttr

func (date *Date) MarshalXMLAttr(name xml.Name) (xml.Attr, error)

MarshalXMLAttr implements encoding/xml.MarshalerAttr by writing the text of MarshalText, and no attribute for a nil pointer, because encoding/xml calls MarshalText through a nil pointer attribute field and panics.

func (Date) Midnight

func (date Date) Midnight() time.Time

Midnight returns the midnight (00:00) time.Time of the date in the local time zone. Returns a zero time.Time if the date is not valid.

func (Date) MidnightInLocation

func (date Date) MidnightInLocation(loc *time.Location) time.Time

MidnightInLocation returns the midnight (00:00) time.Time of the date in the given location. Returns a zero time.Time if the date is zero or not valid. A valid date that is not in the normalized form is normalized first.

func (Date) MidnightUTC

func (date Date) MidnightUTC() time.Time

MidnightUTC returns the midnight (00:00) time.Time of the date in UTC, or a zero time.Time value if the date is zero or not valid. A valid date that is not in the normalized form is normalized first.

func (Date) Month

func (date Date) Month() time.Month

Month returns the month component of the date. Returns 0 if the date is not valid.

func (Date) NextSunday

func (date Date) NextSunday() Date

NextSunday returns the date of the Sunday on or after this date.

func (Date) Normalized

func (date Date) Normalized() (Date, error)

Normalized returns the date in normalized form, or an error if the format can't be detected or the date is zero, see IsZero. Returns the Date unchanged in case of an error. Normalized implements types.Normalizable[Date], use NormalizedLang to pass a language hint.

func (Date) NormalizedEqual

func (date Date) NormalizedEqual(other Date) bool

NormalizedEqual returns true if two dates are equal after normalization. An invalid date (including "") has no normalized value and is not equal to any date, not even to an identical invalid string.

func (Date) NormalizedLang

func (date Date) NormalizedLang(lang language.Code) (Date, error)

NormalizedLang returns the date in normalized form like Normalized, with lang as hint for the order of day and month in an ambiguous numeric date with slashes: language.EN reads "05/06/2024" month first and every other language day first. Other separators, like in "05.06.2024", are read day first with any hint. An empty lang or one that can't be normalized gives no hint, then slashes are read month first, see Normalize. Returns the Date unchanged in case of an error.

func (Date) NormalizedOrNull

func (date Date) NormalizedOrNull(lang ...language.Code) NullableDate

NormalizedOrNull returns the normalized date as NullableDate if possible, otherwise returns Null. The first given lang argument is used as language hint for parsing.

func (Date) NormalizedOrUnchanged

func (date Date) NormalizedOrUnchanged(lang ...language.Code) Date

NormalizedOrUnchanged returns the normalized date if possible, otherwise returns the date unchanged. The first given lang argument is used as language hint for parsing.

func (Date) Nullable

func (date Date) Nullable() NullableDate

Nullable returns the date as a NullableDate. Returns Null if the date is zero, otherwise returns the date as NullableDate.

func (*Date) Scan

func (date *Date) Scan(value any) error

Scan implements the database/sql.Scanner interface. A valid date from a string or []byte is stored normalized, SQL NULL and a zero date (see IsZero) as "", and a date that can't be normalized unchanged without an error, so that one invalid value doesn't fail a whole query; Validate reports it. A time.Time is stored as OfTime, which is already YYYY-MM-DD or "" for the zero time, without parsing it again.

func (*Date) ScanString

func (date *Date) ScanString(source string, validate bool) error

ScanString implements the strfmt.Scannable interface. Without validate it trims surrounding whitespace, including a zero date. With validate it stores the normalized date or returns the error of Normalized, also for a blank or zero source.

func (*Date) ScanStringWithLang

func (date *Date) ScanStringWithLang(source string, lang language.Code) (wasNormalized bool, monthMustBeFirst bool, err error)

ScanStringWithLang parses and assigns the source string as a Date using the given language hint. Returns wasNormalized to indicate if the source was already in normalized form, monthMustBeFirst to indicate if the date format requires month-first ordering, and an error if parsing fails, also for a blank source. A zero date in any spelling, see IsZero, is assigned as "" like by Scan. monthMustBeFirst is only true if month first is the only valid reading, like for "12/25/2023", not for an ambiguous date like "05/06/2024" that is read month first because of its slashes or the hint.

func (Date) Sub

func (date Date) Sub(other Date) time.Duration

Sub returns the duration between the date and the other date (date - other).

func (Date) Time

func (date Date) Time(hour, minute, second int, location *time.Location) time.Time

Time returns a time.Time for the date at the specified hour, minute, and second in the given location. Returns a zero time.Time if the date is zero. An invalid date is not detected and results in a meaningless time before year 1 (from time.Date(0, 0, 0, ...)), use Valid to check the date first.

func (Date) TimeLocal

func (date Date) TimeLocal(hour, minute, second int) time.Time

TimeLocal returns a time.Time for the date at the specified hour, minute, and second in local time. Returns a zero time.Time if the date is zero, see Time for invalid dates.

func (Date) TimeUTC

func (date Date) TimeUTC(hour, minute, second int) time.Time

TimeUTC returns a time.Time for the date at the specified hour, minute, and second in UTC. Returns a zero time.Time if the date is zero, see Time for invalid dates.

func (*Date) UnmarshalJSON

func (date *Date) UnmarshalJSON(data []byte) error

UnmarshalJSON implements encoding/json.Unmarshaler. A JSON string is stored with surrounding whitespace trimmed. A zero date is stored as "", like Scan. JSON null leaves the Date unchanged like encoding/json does for a string type, and any other JSON value is an error.

func (*Date) UnmarshalXML

func (date *Date) UnmarshalXML(d *xml.Decoder, start xml.StartElement) error

UnmarshalXML implements encoding/xml.Unmarshaler by storing the text of the element like UnmarshalJSON stores it.

func (*Date) UnmarshalXMLAttr

func (date *Date) UnmarshalXMLAttr(attr xml.Attr) error

UnmarshalXMLAttr implements encoding/xml.UnmarshalerAttr by storing the attribute value like UnmarshalJSON stores it.

func (Date) Valid

func (date Date) Valid() bool

Valid returns true if the date is in a valid, normalizable format.

func (Date) ValidAndNormalized

func (date Date) ValidAndNormalized() bool

ValidAndNormalized returns true if the date is both valid and already in normalized form (YYYY-MM-DD).

func (Date) Validate

func (date Date) Validate() error

Validate returns an error if the date is not in a valid, normalizable format.

func (Date) Value

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

Value implements the database/sql/driver.Valuer interface. It returns the normalized date, SQL NULL for a zero date (see IsZero), or the error of Normalized for a date that can't be normalized.

func (Date) Weekday

func (date Date) Weekday() time.Weekday

Weekday returns the day of the week for this date. Returns 0 (Sunday) if the date is not valid.

func (Date) WithinIncl

func (date Date) WithinIncl(from, until Date) bool

WithinIncl returns true if the date is within the inclusive range [from, until]. Returns false if any of the dates is not valid, see After.

func (Date) Year

func (date Date) Year() int

Year returns the year component of the date. Returns 0 if the date is not valid.

func (Date) YearMonthDay

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

YearMonthDay returns the year, month, and day components of the date. Returns zero values if the date is not valid.

type Finder

type Finder struct {
	LangHint language.Code
}

Finder scans arbitrary text for substrings that can be parsed as dates. Use NewFinder to create one, optionally with a language hint to resolve ambiguous day/month orderings.

func NewFinder

func NewFinder(lang ...language.Code) *Finder

NewFinder returns a Finder that uses the first element of lang as a language hint when parsing date candidates. The hint is used to disambiguate ambiguous dd/mm vs mm/dd orderings with slashes like Normalize: language.EN reads "05/06/2024" month first, every other language day first, and without a hint it is read month first. "05.06.2024" with dots or any other separator is read day first with every hint.

func (*Finder) FindAllIndex

func (df *Finder) FindAllIndex(str []byte, n int) (indices [][]int)

FindAllIndex returns the byte-index pairs [start, end) of every date found in str, trying spans of up to three whitespace-delimited words at a time. A span is a date if Normalize accepts it, so an ISO 8601 date-time like "2023-12-25T10:00:00Z" is found as a whole. Only the Italian and Spanish month abbreviations that are common words in other languages, like "set" and "ago", need language.IT or language.ES as LangHint, so that text like "Game set 10 2020" has no date. At most n results are returned; pass n < 0 to return all matches. The returned slice is nil when no dates are found.

type Format

type Format struct {
	Layout     string `json:"layout"`     // The time layout string for formatting
	NilString  string `json:"nilString"`  // String to use for nil values
	ZeroString string `json:"zeroString"` // String to use for zero values
}

Format provides date formatting and parsing capabilities with customizable layouts.

func (*Format) AssignString

func (f *Format) AssignString(dest reflect.Value, source string) error

AssignString assigns a string value to various date-related types using reflection.

func (*Format) Format

func (f *Format) Format(date Date) string

Format formats a Date using the configured layout.

func (*Format) FormatString

func (f *Format) FormatString(val reflect.Value) (string, error)

FormatString formats a value as a date string using the configured layout.

func (*Format) Parse

func (f *Format) Parse(str string, langHints ...language.Code) (normalized string, err error)

Parse implements the strfmt.Parser interface for date parsing.

type Formatter

type Formatter string

Formatter is a date layout string (compatible with time.Time.Format) that can format Date values and parse date strings. It implements the strfmt.Parser interface (but not strfmt.Formatter) so it can be used with generic parsing pipelines.

func (Formatter) Format

func (f Formatter) Format(date Date) string

Format formats date using f as the layout string (see time.Time.Format). Returns an empty string if f or date are empty.

func (Formatter) Parse

func (f Formatter) Parse(str string, langHints ...language.Code) (normalized string, err error)

Parse implements the strfmt.Parser interface

type NullableDate

type NullableDate string

NullableDate is identical to Date, except that a zero date (see Date.IsZero) is null and considered valid by the Valid() and Validate() methods. The main difference between Date and NullableDate is: Date("").Valid() == false NullableDate("").Valid() == true

NullableDate reads and writes like Date, except that null is SQL NULL and JSON null. See "Reading and writing values" in the README of the module.

const Null NullableDate = ""

Null is an empty string and will be treated as SQL NULL. date.Null.IsZero() == true

func MustNullable

func MustNullable(str string) NullableDate

MustNullable returns str as normalized NullableDate or panics if str is not neither a valid Date nor Null ("").

func NormalizeNullable

func NormalizeNullable(str string, lang ...language.Code) (NullableDate, error)

NormalizeNullable returns str as normalized NullableDate or an error. The first given lang argument is used as language hint for parsing.

func OfTimePtr

func OfTimePtr(t *time.Time) NullableDate

OfTimePtr returns the date part of the passed time.Time or Null (an empty string) if t is nil or t.IsZero().

func (NullableDate) Add

Add returns a new date with the specified duration added. Returns Null if the NullableDate is null.

func (NullableDate) AddDate

func (n NullableDate) AddDate(years int, months int, days int) NullableDate

AddDate returns a new date with the specified years, months, and days added. Returns Null if the NullableDate is null.

func (NullableDate) AddDays

func (n NullableDate) AddDays(days int) NullableDate

AddDays returns a new date with the specified number of days added. Returns Null if the NullableDate is null.

func (NullableDate) AddMonths

func (n NullableDate) AddMonths(months int) NullableDate

AddMonths returns a new date with the specified number of months added. Returns Null if the NullableDate is null.

func (NullableDate) AddYears

func (n NullableDate) AddYears(years int) NullableDate

AddYears returns a new date with the specified number of years added. Returns Null if the NullableDate is null.

func (NullableDate) After

func (n NullableDate) After(other NullableDate) bool

After returns true if the date is after the other date. A null date is always before any non-null date, so any non-null date is after a null date and a null date is never after any date. Returns false if either date is not null and not valid, see Date.After.

func (NullableDate) AfterTime

func (n NullableDate) AfterTime(other time.Time) bool

AfterTime returns true if midnight of the date (in the location of the passed time) is after the time. Returns false if the date is null or not valid, see Date.After.

func (NullableDate) AfterToday

func (n NullableDate) AfterToday() bool

AfterToday returns true if the date is after today in local time. Returns false if the date is null.

func (NullableDate) AfterTodayInUTC

func (n NullableDate) AfterTodayInUTC() bool

AfterTodayInUTC returns true if the date is after today in UTC time. Returns false if the date is null.

func (NullableDate) Before

func (n NullableDate) Before(other NullableDate) bool

Before returns true if the date is before the other date. A null date is always before any non-null date. Returns false if either date is not null and not valid, see Date.After.

func (NullableDate) BeforeTime

func (n NullableDate) BeforeTime(other time.Time) bool

BeforeTime returns true if midnight of the date (in the location of the passed time) is before the time. Returns true if the date is null and the time is not zero, and false if the date is not valid, see Date.After.

func (NullableDate) BeforeToday

func (n NullableDate) BeforeToday() bool

BeforeToday returns true if the date is before today in local time. A null date is always before today.

func (NullableDate) BeforeTodayInUTC

func (n NullableDate) BeforeTodayInUTC() bool

BeforeTodayInUTC returns true if the date is before today in UTC time. A null date is always before today.

func (NullableDate) BeginningOfMonth

func (n NullableDate) BeginningOfMonth() NullableDate

BeginningOfMonth returns the date of the first day of the month containing this date. Returns Null if the NullableDate is null.

func (NullableDate) BeginningOfQuarter

func (n NullableDate) BeginningOfQuarter() NullableDate

BeginningOfQuarter returns the date of the first day of the quarter containing this date. Returns Null if the NullableDate is null.

func (NullableDate) BeginningOfWeek

func (n NullableDate) BeginningOfWeek(startDay time.Weekday) NullableDate

BeginningOfWeek returns the date of the first day of the week containing this date. The startDay parameter specifies which day is considered the start of the week. Returns Null if the NullableDate is null.

func (NullableDate) BeginningOfYear

func (n NullableDate) BeginningOfYear() NullableDate

BeginningOfYear returns the date of the first day of the year containing this date. Returns Null if the NullableDate is null.

func (NullableDate) Compare

func (n NullableDate) Compare(other NullableDate) int

Compare compares the date with another NullableDate. Returns -1 if n is before other, +1 if after, 0 if equal. A null date is always before a non-null date. An invalid date compares like Null, see Date.Compare.

func (NullableDate) Date

func (n NullableDate) Date() Date

Date returns the NullableDate as Date without checking if it's null. See also Get which panics on null.

func (NullableDate) DateOr

func (n NullableDate) DateOr(useIfNull Date) Date

DateOr returns the NullableDate as Date if it is not null, else useIfNull will be returned.

func (NullableDate) Day

func (n NullableDate) Day() int

Day returns the day of the month component of the date. Returns 0 if the date is null.

func (NullableDate) EndOfMonth

func (n NullableDate) EndOfMonth() NullableDate

EndOfMonth returns the date of the last day of the month containing this date. Returns Null if the NullableDate is null.

func (NullableDate) EndOfQuarter

func (n NullableDate) EndOfQuarter() NullableDate

EndOfQuarter returns the date of the last day of the quarter containing this date. Returns Null if the NullableDate is null.

func (NullableDate) EndOfWeek

func (n NullableDate) EndOfWeek(weekday time.Weekday) NullableDate

EndOfWeek returns the date of the last day of the week containing this date. The weekday parameter specifies which day is considered the start of the week. Returns Null if the NullableDate is null.

func (NullableDate) EndOfYear

func (n NullableDate) EndOfYear() NullableDate

EndOfYear returns the date of the last day of the year containing this date. Returns Null if the NullableDate is null.

func (NullableDate) EqualOrAfter

func (n NullableDate) EqualOrAfter(other NullableDate) bool

EqualOrAfter returns true if the date is equal to or after the other date.

func (NullableDate) EqualOrBefore

func (n NullableDate) EqualOrBefore(other NullableDate) bool

EqualOrBefore returns true if the date is equal to or before the other date.

func (NullableDate) Format

func (n NullableDate) Format(layout string) string

Format returns the date formatted like Date.Format, or an empty string if n is null (see IsNull) or layout is an empty string. A date that is not valid is returned unchanged.

func (NullableDate) Get

func (n NullableDate) Get() Date

Get returns the non-nullable Date value or panics if the NullableDate is null. Note: check with IsNull before using Get!

func (NullableDate) GetOr

func (n NullableDate) GetOr(defaultDate Date) Date

GetOr returns the non-nullable Date value or the passed defaultDate if the NullableDate is null.

func (NullableDate) ISOWeek

func (n NullableDate) ISOWeek() (year, week int)

ISOWeek returns the ISO 8601 year and week number in which the date 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. Returns zeros if the date is not valid or null.

func (NullableDate) IsNotNull

func (n NullableDate) IsNotNull() bool

IsNotNull returns true if the NullableDate is not null.

func (NullableDate) IsNull

func (n NullableDate) IsNull() bool

IsNull returns true if the NullableDate is null or zero, see Date.IsZero, which includes a string of only the runes strutil.TrimSpace removes like for country.NullableCode, and a zero date in another format like "01.01.0001". IsNull implements the nullable.Nullable interface.

func (NullableDate) IsToday

func (n NullableDate) IsToday() bool

IsToday returns true if the date is today in local time. Returns false if the date is null.

func (NullableDate) IsTodayInUTC

func (n NullableDate) IsTodayInUTC() bool

IsTodayInUTC returns true if the date is today in UTC time. Returns false if the date is null.

func (NullableDate) IsZero

func (n NullableDate) IsZero() bool

IsZero returns true if the date is zero like Date.IsZero, which is the same as IsNull.

func (NullableDate) JSONSchema

func (NullableDate) JSONSchema() *jsonschema.Schema

JSONSchema returns the JSON schema definition for the NullableDate type. Implements the jsonschema.JSONSchemaProvider interface.

func (NullableDate) LastMonday

func (n NullableDate) LastMonday() NullableDate

LastMonday returns the date of the Monday on or before this date. Returns Null if the NullableDate is null.

func (NullableDate) MarshalJSON

func (n NullableDate) MarshalJSON() ([]byte, error)

MarshalJSON implements encoding/json.Marshaler by writing JSON null if the NullableDate is blank, else the date with surrounding whitespace trimmed. A zero date is written as JSON null, like Value writes SQL NULL.

func (NullableDate) MarshalText

func (n NullableDate) MarshalText() ([]byte, error)

MarshalText implements encoding.TextMarshaler like MarshalJSON, but with "" for null, so that encoding/xml and strfmt write the trimmed date. encoding/json writes map keys of string types as they are and doesn't call MarshalText for them.

func (*NullableDate) MarshalXMLAttr

func (n *NullableDate) MarshalXMLAttr(name xml.Name) (xml.Attr, error)

MarshalXMLAttr implements encoding/xml.MarshalerAttr by writing the text of MarshalText, and no attribute for a nil pointer, because encoding/xml calls MarshalText through a nil pointer attribute field and panics.

func (NullableDate) Midnight

func (n NullableDate) Midnight() nullable.Time

Midnight returns the midnight (00:00) nullable.Time of the date in the local time zone, or a null nullable.Time value if the date is not valid.

func (NullableDate) MidnightInLocation

func (n NullableDate) MidnightInLocation(loc *time.Location) nullable.Time

MidnightInLocation returns the midnight (00:00) nullable.Time of the date in the given location. Returns a null nullable.Time if the date is not valid or null. A valid date that is not in the normalized form is normalized first.

func (NullableDate) MidnightUTC

func (n NullableDate) MidnightUTC() nullable.Time

MidnightUTC returns the midnight (00:00) nullable.Time of the date in UTC, or a null nullable.Time value if the date is null or not valid. A valid date that is not in the normalized form is normalized first.

func (NullableDate) Month

func (n NullableDate) Month() time.Month

Month returns the month component of the date. Returns 0 if the date is null.

func (NullableDate) NextSunday

func (n NullableDate) NextSunday() NullableDate

NextSunday returns the date of the Sunday on or after this date. Returns Null if the NullableDate is null.

func (NullableDate) Normalized

func (n NullableDate) Normalized() (NullableDate, error)

Normalized returns the date in normalized form, or an error if the format can't be detected. If n.IsNull() then Null, nil will be returned. Returns the NullableDate unchanged in case of an error. Normalized implements types.Normalizable[NullableDate], use NormalizedLang to pass a language hint.

func (NullableDate) NormalizedEqual

func (n NullableDate) NormalizedEqual(other NullableDate) bool

NormalizedEqual returns true if two dates are equal after normalization. Null and the zero dates are equal to each other. An invalid date has no normalized value and is not equal to any date, not even to Null or an identical invalid string.

func (NullableDate) NormalizedLang

func (n NullableDate) NormalizedLang(lang language.Code) (NullableDate, error)

NormalizedLang returns the date in normalized form like Normalized, with lang as hint for the order of day and month like Date.NormalizedLang.

func (NullableDate) NormalizedOrNull

func (n NullableDate) NormalizedOrNull(lang ...language.Code) NullableDate

NormalizedOrNull returns the normalized date as NullableDate if possible, otherwise returns Null. The first given lang argument is used as language hint for parsing.

func (NullableDate) NormalizedOrUnchanged

func (n NullableDate) NormalizedOrUnchanged(lang ...language.Code) NullableDate

NormalizedOrUnchanged returns the normalized date if possible, otherwise returns the date unchanged. The first given lang argument is used as language hint for parsing.

func (*NullableDate) Scan

func (n *NullableDate) Scan(value any) error

Scan implements the database/sql.Scanner interface. A valid date from a string or []byte is stored normalized, SQL NULL and a zero date (see IsNull) as Null, and a date that can't be normalized unchanged without an error, so that one invalid value doesn't fail a whole query; Validate reports it. A time.Time is stored as OfTime, which is already YYYY-MM-DD or Null for the zero time, without parsing it again.

func (*NullableDate) ScanString

func (n *NullableDate) ScanString(source string, validate bool) error

ScanString implements the strfmt.Scannable interface. The strings "NULL", "null" and "nil" set the NullableDate to null. Without validate it stores source with surrounding whitespace trimmed, including a zero date. With validate it stores the normalized date or returns the error of Normalized.

func (*NullableDate) ScanStringWithLang

func (n *NullableDate) ScanStringWithLang(source string, lang language.Code) (wasNormalized bool, monthMustBeFirst bool, err error)

ScanStringWithLang parses and assigns the source string as a NullableDate using the given language hint. Returns wasNormalized to indicate if the source was already in normalized form, monthMustBeFirst to indicate if the date format requires month-first ordering like Date.ScanStringWithLang, and an error if parsing fails. Null values (empty, whitespace only or zero) are treated as Null.

func (*NullableDate) Set

func (n *NullableDate) Set(d Date)

Set sets a Date for this NullableDate.

func (*NullableDate) SetNull

func (n *NullableDate) SetNull()

SetNull sets the NullableDate to null.

func (NullableDate) StringOr

func (n NullableDate) StringOr(nullString string) string

StringOr returns the NullableDate as stored, or the passed nullString if the NullableDate is null.

func (NullableDate) Sub

func (n NullableDate) Sub(other NullableDate) time.Duration

Sub returns the duration between the date and the other date (n - other). Returns 0 if either date is null or both dates are equal.

func (*NullableDate) UnmarshalJSON

func (n *NullableDate) UnmarshalJSON(data []byte) error

UnmarshalJSON implements encoding/json.Unmarshaler. A JSON string is stored with surrounding whitespace trimmed, including a zero date, unlike Scan. JSON null sets the NullableDate to null, so that decoding null into a field that holds a value resets it, and any other JSON value is an error.

func (*NullableDate) UnmarshalXML

func (n *NullableDate) UnmarshalXML(d *xml.Decoder, start xml.StartElement) error

UnmarshalXML implements encoding/xml.Unmarshaler by storing the text of the element like UnmarshalJSON stores it.

func (*NullableDate) UnmarshalXMLAttr

func (n *NullableDate) UnmarshalXMLAttr(attr xml.Attr) error

UnmarshalXMLAttr implements encoding/xml.UnmarshalerAttr by storing the attribute value like UnmarshalJSON stores it.

func (NullableDate) Valid

func (n NullableDate) Valid() bool

Valid returns if the format of the date is correct, see Format. A null date is valid, see IsNull.

func (NullableDate) ValidAndNormalized

func (n NullableDate) ValidAndNormalized() bool

ValidAndNormalized returns if the date is valid and already normalized.

func (NullableDate) ValidAndNotNull

func (n NullableDate) ValidAndNotNull() bool

ValidAndNotNull returns if the date is valid and not Null or Zero.

func (NullableDate) Validate

func (n NullableDate) Validate() error

Validate returns an error if the date is not in a valid, normalizable format. A null date is valid, see IsNull.

func (NullableDate) Value

func (n NullableDate) Value() (driver.Value, error)

Value implements the database/sql/driver.Valuer interface. It returns the normalized date, SQL NULL if the NullableDate is null, or the error of Normalized for a date that can't be normalized.

func (NullableDate) Weekday

func (n NullableDate) Weekday() time.Weekday

Weekday returns the day of the week for this date. Returns 0 (Sunday) if the date is null.

func (NullableDate) Year

func (n NullableDate) Year() int

Year returns the year component of the date. Returns 0 if the date is null.

func (NullableDate) YearMonthDay

func (n NullableDate) YearMonthDay() (year int, month time.Month, day int)

YearMonthDay returns the year, month, and day components of the date. Returns zero values if the date is not valid or null.

type NullableYearMonth

type NullableYearMonth string

NullableYearMonth is a year-month string in YYYY-MM format that can also represent a NULL value as an empty string.

const YearMonthNull NullableYearMonth = ""

YearMonthNull is the null value for NullableYearMonth (empty string). Value writes it as SQL NULL and MarshalJSON as JSON null.

func (NullableYearMonth) AddMonths

func (ym NullableYearMonth) AddMonths(months int) NullableYearMonth

AddMonths returns a new NullableYearMonth with the specified number of months added. Returns null if the NullableYearMonth is null and an invalid NullableYearMonth unchanged. Handles month overflow by adjusting the year accordingly.

func (NullableYearMonth) AddYears

func (ym NullableYearMonth) AddYears(years int) NullableYearMonth

AddYears returns a new NullableYearMonth with the specified number of years added. Returns null if the NullableYearMonth is null and an invalid NullableYearMonth unchanged.

func (NullableYearMonth) Compare

func (ym NullableYearMonth) Compare(other NullableYearMonth) int

Compare compares the normalized year-month with another normalized NullableYearMonth, an invalid one as it is. Null is before every year-month. Returns -1 if ym is before other, +1 if after, 0 if equal.

func (NullableYearMonth) ContainsDate

func (ym NullableYearMonth) ContainsDate(date Date) bool

ContainsDate returns true if the given date falls within this year-month. Returns false if the NullableYearMonth is null.

func (NullableYearMonth) ContainsTime

func (ym NullableYearMonth) ContainsTime(t time.Time) bool

ContainsTime returns true if the given time falls within this year-month. Returns false if the NullableYearMonth is null.

func (NullableYearMonth) Date

func (ym NullableYearMonth) Date(day int) NullableDate

Date returns a NullableDate for the given day within this year-month. Returns Null if the NullableYearMonth is null. The day value is formatted as-is without validation.

func (NullableYearMonth) DateRange

func (ym NullableYearMonth) DateRange() (fromDate, untilDate NullableDate)

DateRange returns the first and last NullableDate of the month. Returns Null dates if the NullableYearMonth is null or not valid. Returns the date range [fromDate, untilDate] representing the entire month.

func (NullableYearMonth) Format

func (ym NullableYearMonth) Format(layout string) string

Format formats the year-month using the given layout string (see time.Time.Format). Returns an empty string if ym or layout are empty, or if ym is null. If layout equals YearMonthLayout constant, returns the normalized year-month, or an invalid one unchanged. For other layouts, converts to Date using the 1st day of the month and delegates to Date.Format.

func (NullableYearMonth) Get

func (ym NullableYearMonth) Get() YearMonth

Get returns the non-nullable YearMonth value or panics if the NullableYearMonth is null. Note: check with IsNull before using Get!

func (NullableYearMonth) GetOr

func (ym NullableYearMonth) GetOr(defaultYearMonth YearMonth) YearMonth

GetOr returns the non-nullable YearMonth value or the passed defaultYearMonth if the NullableYearMonth is null.

func (NullableYearMonth) IsNotNull

func (ym NullableYearMonth) IsNotNull() bool

IsNotNull returns true if the NullableYearMonth is not null, see IsNull.

func (NullableYearMonth) IsNull

func (ym NullableYearMonth) IsNull() bool

IsNull returns true if the NullableYearMonth is empty or whitespace only. A zero period such as "0001-01" is kept and is not null, so Get returns it and callers that skip null values do not drop a stored period. IsNull implements the nullable.Nullable interface.

func (NullableYearMonth) IsZero

func (ym NullableYearMonth) IsZero() bool

IsZero returns true if the year-month is zero like YearMonth.IsZero. A zero period such as "0001-01" is not null: reading and writing keep that text, and IsNull is false for it.

func (NullableYearMonth) JSONSchema

func (NullableYearMonth) JSONSchema() *jsonschema.Schema

JSONSchema returns the JSON schema definition for the NullableYearMonth type. Implements the jsonschema.JSONSchemaProvider interface.

func (NullableYearMonth) MarshalJSON

func (ym NullableYearMonth) MarshalJSON() ([]byte, error)

MarshalJSON implements encoding/json.Marshaler by writing JSON null if the NullableYearMonth is blank, else the trimmed year-month. A zero year-month is written as that text.

func (NullableYearMonth) MarshalText

func (ym NullableYearMonth) MarshalText() ([]byte, error)

MarshalText implements encoding.TextMarshaler like MarshalJSON, but with "" for null, so that encoding/xml and strfmt write the trimmed year-month, including a zero period. encoding/json writes map keys of string types as they are and doesn't call MarshalText for them.

func (*NullableYearMonth) MarshalXMLAttr

func (ym *NullableYearMonth) MarshalXMLAttr(name xml.Name) (xml.Attr, error)

MarshalXMLAttr implements encoding/xml.MarshalerAttr by writing the text of MarshalText, and no attribute for a nil pointer, because encoding/xml calls MarshalText through a nil pointer attribute field and panics.

func (NullableYearMonth) Month

func (ym NullableYearMonth) Month() time.Month

Month returns the month component of the year-month. Returns 0 if the year-month is null or not valid.

func (NullableYearMonth) Normalized

func (ym NullableYearMonth) Normalized() (NullableYearMonth, error)

Normalized returns YearMonthNull for a null year-month, see IsNull, else the year-month normalized like YearMonth.Normalized, or unchanged together with an error if it can't be normalized.

func (*NullableYearMonth) Scan

func (ym *NullableYearMonth) Scan(value any) error

Scan implements the database/sql.Scanner interface. Surrounding whitespace is trimmed. A time.Time is stored as its year-month, and the zero time.Time as YearMonthNull. SQL NULL and a blank string are YearMonthNull. A zero year-month such as "0001-01" is kept. An invalid year-month is kept after the trim, without an error.

func (*NullableYearMonth) ScanString

func (ym *NullableYearMonth) ScanString(source string, validate bool) error

ScanString implements the strfmt.Scannable interface. The strings "NULL", "null" and "nil" set the NullableYearMonth to null. Without validate it stores source like Scan, with validate it stores the normalized year-month or returns the error of Normalized.

func (*NullableYearMonth) Set

func (ym *NullableYearMonth) Set(yearMonth YearMonth)

Set sets a YearMonth for this NullableYearMonth.

func (*NullableYearMonth) SetNull

func (ym *NullableYearMonth) SetNull()

SetNull sets the NullableYearMonth to null.

func (NullableYearMonth) String

func (ym NullableYearMonth) String() string

String returns the year-month as a string in YYYY-MM format. String implements the fmt.Stringer interface.

func (NullableYearMonth) StringOr

func (ym NullableYearMonth) StringOr(nullString string) string

StringOr returns the NullableYearMonth as string or the passed nullString if the NullableYearMonth is null.

func (*NullableYearMonth) UnmarshalJSON

func (ym *NullableYearMonth) UnmarshalJSON(data []byte) error

UnmarshalJSON implements encoding/json.Unmarshaler. A JSON string is stored like Scan stores it, JSON null sets the NullableYearMonth to null, so that decoding null into a field that holds a value resets it, and any other JSON value is an error.

func (*NullableYearMonth) UnmarshalXML

func (ym *NullableYearMonth) UnmarshalXML(d *xml.Decoder, start xml.StartElement) error

UnmarshalXML implements encoding/xml.Unmarshaler by storing the text of the element like Scan stores it.

func (*NullableYearMonth) UnmarshalXMLAttr

func (ym *NullableYearMonth) UnmarshalXMLAttr(attr xml.Attr) error

UnmarshalXMLAttr implements encoding/xml.UnmarshalerAttr by storing the attribute value like Scan stores it.

func (NullableYearMonth) Valid

func (ym NullableYearMonth) Valid() bool

Valid returns true if the year-month is null or can be normalized, see YearMonth.Validate.

func (NullableYearMonth) ValidAndNormalized

func (ym NullableYearMonth) ValidAndNormalized() bool

ValidAndNormalized returns true if the year-month is valid and already normalized, or if it is the empty YearMonthNull. A whitespace-only or zero value is null and valid, but not normalized.

func (NullableYearMonth) ValidAndNotNull

func (ym NullableYearMonth) ValidAndNotNull() bool

ValidAndNotNull returns if the year-month is valid and not null, see IsNull.

func (NullableYearMonth) Validate

func (ym NullableYearMonth) Validate() error

Validate returns nil if the year-month is null or can be normalized, see YearMonth.Validate.

func (NullableYearMonth) Value

func (ym NullableYearMonth) Value() (driver.Value, error)

Value implements the database/sql/driver.Valuer interface. It returns the trimmed year-month, or SQL NULL for a blank one. A zero year-month such as "0001-01" is written as that text. An invalid year-month is written after the trim, not rejected.

func (NullableYearMonth) Year

func (ym NullableYearMonth) Year() int

Year returns the year component of the year-month. Returns 0 if the year-month is null or not valid.

type NullableYearQuarter

type NullableYearQuarter string

NullableYearQuarter is a year-quarter string in YYYY-Q# format (e.g. "2024-Q3") that can also represent a NULL value as an empty string.

const YearQuarterNull NullableYearQuarter = ""

YearQuarterNull is the null value for NullableYearQuarter (empty string). Value writes it as SQL NULL and MarshalJSON as JSON null.

func (NullableYearQuarter) AddQuarters

func (yq NullableYearQuarter) AddQuarters(quarters int) NullableYearQuarter

AddQuarters returns a new NullableYearQuarter with the specified number of quarters added. Returns null if the NullableYearQuarter is null and an invalid NullableYearQuarter unchanged. Handles quarter overflow by adjusting the year accordingly.

func (NullableYearQuarter) AddYears

func (yq NullableYearQuarter) AddYears(years int) NullableYearQuarter

AddYears returns a new NullableYearQuarter with the specified number of years added. Returns null if the NullableYearQuarter is null and an invalid NullableYearQuarter unchanged.

func (NullableYearQuarter) Compare

func (yq NullableYearQuarter) Compare(other NullableYearQuarter) int

Compare compares the normalized year-quarter with another normalized NullableYearQuarter, an invalid one as it is. Null is before every year-quarter. Returns -1 if yq is before other, +1 if after, 0 if equal.

func (NullableYearQuarter) ContainsDate

func (yq NullableYearQuarter) ContainsDate(date Date) bool

ContainsDate returns true if the given date falls within this year-quarter. Returns false if the NullableYearQuarter is null.

func (NullableYearQuarter) ContainsTime

func (yq NullableYearQuarter) ContainsTime(t time.Time) bool

ContainsTime returns true if the given time falls within this year-quarter. Returns false if the NullableYearQuarter is null.

func (NullableYearQuarter) ContainsYearMonth

func (yq NullableYearQuarter) ContainsYearMonth(ym YearMonth) bool

ContainsYearMonth returns true if the given year-month falls within this year-quarter. Returns false if the NullableYearQuarter is null.

func (NullableYearQuarter) Date

func (yq NullableYearQuarter) Date(monthInQuarter, day int) NullableDate

Date returns a NullableDate for the given month (1-3 within quarter) and day. Returns Null if the NullableYearQuarter is null or not valid.

func (NullableYearQuarter) DateRange

func (yq NullableYearQuarter) DateRange() (fromDate, untilDate NullableDate)

DateRange returns the first and last NullableDate of the quarter. Returns Null dates if the NullableYearQuarter is null or not valid.

func (NullableYearQuarter) FirstMonth

func (yq NullableYearQuarter) FirstMonth() time.Month

FirstMonth returns the first month of the quarter. Returns 0 if the year-quarter is null or not valid.

func (NullableYearQuarter) Get

Get returns the non-nullable YearQuarter value or panics if the NullableYearQuarter is null. Note: check with IsNull before using Get!

func (NullableYearQuarter) GetOr

func (yq NullableYearQuarter) GetOr(defaultYearQuarter YearQuarter) YearQuarter

GetOr returns the non-nullable YearQuarter value or the passed defaultYearQuarter if the NullableYearQuarter is null.

func (NullableYearQuarter) IsNotNull

func (yq NullableYearQuarter) IsNotNull() bool

IsNotNull returns true if the NullableYearQuarter is not null, see IsNull.

func (NullableYearQuarter) IsNull

func (yq NullableYearQuarter) IsNull() bool

IsNull returns true if the NullableYearQuarter is empty or whitespace only. A zero period such as "0001-Q1" is kept and is not null, so Get returns it. IsNull implements the nullable.Nullable interface.

func (NullableYearQuarter) IsZero

func (yq NullableYearQuarter) IsZero() bool

IsZero returns true if the year-quarter is zero like YearQuarter.IsZero. A zero period such as "0001-Q1" is not null: reading and writing keep that text, and IsNull is false for it.

func (NullableYearQuarter) JSONSchema

func (NullableYearQuarter) JSONSchema() *jsonschema.Schema

JSONSchema returns the JSON schema definition for the NullableYearQuarter type. Implements the jsonschema.JSONSchemaProvider interface.

func (NullableYearQuarter) MarshalJSON

func (yq NullableYearQuarter) MarshalJSON() ([]byte, error)

MarshalJSON implements encoding/json.Marshaler by writing JSON null if the NullableYearQuarter is blank, else the trimmed and uppercased year-quarter. A zero year-quarter is written as that text.

func (NullableYearQuarter) MarshalText

func (yq NullableYearQuarter) MarshalText() ([]byte, error)

MarshalText implements encoding.TextMarshaler like MarshalJSON, but with "" for null, so that encoding/xml and strfmt write the trimmed and uppercased year-quarter. encoding/json writes map keys of string types as they are and doesn't call MarshalText for them.

func (*NullableYearQuarter) MarshalXMLAttr

func (yq *NullableYearQuarter) MarshalXMLAttr(name xml.Name) (xml.Attr, error)

MarshalXMLAttr implements encoding/xml.MarshalerAttr by writing the text of MarshalText, and no attribute for a nil pointer, because encoding/xml calls MarshalText through a nil pointer attribute field and panics.

func (NullableYearQuarter) Normalized

func (yq NullableYearQuarter) Normalized() (NullableYearQuarter, error)

Normalized returns YearQuarterNull for a null year-quarter, see IsNull, else the year-quarter normalized like YearQuarter.Normalized, or unchanged together with an error if it can't be normalized.

func (NullableYearQuarter) Quarter

func (yq NullableYearQuarter) Quarter() int

Quarter returns the quarter component of the year-quarter (1-4). Returns 0 if the year-quarter is null or not valid.

func (*NullableYearQuarter) Scan

func (yq *NullableYearQuarter) Scan(value any) error

Scan implements the database/sql.Scanner interface. Surrounding whitespace is trimmed and letters are uppercased. A time.Time is stored as its year-quarter, and the zero time.Time as YearQuarterNull. SQL NULL and a blank string are YearQuarterNull. A zero year-quarter such as "0001-Q1" is kept. An invalid year-quarter is kept after that prettification, without an error.

func (*NullableYearQuarter) ScanString

func (yq *NullableYearQuarter) ScanString(source string, validate bool) error

ScanString implements the strfmt.Scannable interface. The strings "NULL", "null" and "nil" set the NullableYearQuarter to null. Without validate it stores source like Scan, with validate it stores the normalized year-quarter or returns the error of Normalized.

func (*NullableYearQuarter) Set

func (yq *NullableYearQuarter) Set(yearQuarter YearQuarter)

Set sets a YearQuarter for this NullableYearQuarter.

func (*NullableYearQuarter) SetNull

func (yq *NullableYearQuarter) SetNull()

SetNull sets the NullableYearQuarter to null.

func (NullableYearQuarter) String

func (yq NullableYearQuarter) String() string

String returns the year-quarter as a string in YYYY-Q# format. String implements the fmt.Stringer interface.

func (NullableYearQuarter) StringOr

func (yq NullableYearQuarter) StringOr(nullString string) string

StringOr returns the NullableYearQuarter as string or the passed nullString if the NullableYearQuarter is null.

func (*NullableYearQuarter) UnmarshalJSON

func (yq *NullableYearQuarter) UnmarshalJSON(data []byte) error

UnmarshalJSON implements encoding/json.Unmarshaler. A JSON string is stored like Scan stores it, JSON null sets the NullableYearQuarter to null, so that decoding null into a field that holds a value resets it, and any other JSON value is an error.

func (*NullableYearQuarter) UnmarshalXML

func (yq *NullableYearQuarter) UnmarshalXML(d *xml.Decoder, start xml.StartElement) error

UnmarshalXML implements encoding/xml.Unmarshaler by storing the text of the element like Scan stores it.

func (*NullableYearQuarter) UnmarshalXMLAttr

func (yq *NullableYearQuarter) UnmarshalXMLAttr(attr xml.Attr) error

UnmarshalXMLAttr implements encoding/xml.UnmarshalerAttr by storing the attribute value like Scan stores it.

func (NullableYearQuarter) Valid

func (yq NullableYearQuarter) Valid() bool

Valid returns true if the year-quarter is null or can be normalized, see YearQuarter.Validate.

func (NullableYearQuarter) ValidAndNormalized

func (yq NullableYearQuarter) ValidAndNormalized() bool

ValidAndNormalized returns true if the year-quarter is valid and already normalized, or if it is the empty YearQuarterNull. A whitespace-only or zero value is null and valid, but not normalized.

func (NullableYearQuarter) ValidAndNotNull

func (yq NullableYearQuarter) ValidAndNotNull() bool

ValidAndNotNull returns if the year-quarter is valid and not null, see IsNull.

func (NullableYearQuarter) Validate

func (yq NullableYearQuarter) Validate() error

Validate returns nil if the year-quarter is null or can be normalized, see YearQuarter.Validate.

func (NullableYearQuarter) Value

func (yq NullableYearQuarter) Value() (driver.Value, error)

Value implements the database/sql/driver.Valuer interface. It returns the trimmed and uppercased year-quarter, or SQL NULL for a blank one. A zero year-quarter such as "0001-Q1" is written as that text. An invalid year-quarter is written after that prettification, not rejected.

func (NullableYearQuarter) Year

func (yq NullableYearQuarter) Year() int

Year returns the year component of the year-quarter. Returns 0 if the year-quarter is null or not valid.

type Parser

type Parser struct{}

Parser implements the strfmt.Parser interface for dates.

func (Parser) Parse

func (Parser) Parse(str string, langHints ...language.Code) (normalized string, err error)

Parse parses a string as a date and returns the normalized string representation.

type YearMonth

type YearMonth string

YearMonth represents a calendar year and month in ISO 8601 format (YYYY-MM). See NullableYearMonth for a nullable version of this type.

Scan, UnmarshalJSON, UnmarshalXML, MarshalJSON, MarshalText, Value and ScanString without validate trim surrounding whitespace. A zero year-month such as "0001-01" is kept. They do not reject an invalid year-month. A time.Time from the driver is still its year-month, and the zero time.Time is "". Value writes SQL NULL only for a blank year-month. ScanString with validate stores the normalized year-month or returns the error of Normalized. fmt prints the year-month as stored. See "Reading and writing values" in the README of the module.

func YearMonthFrom

func YearMonthFrom(year int, month time.Month) YearMonth

YearMonthFrom creates a YearMonth from the given year and month values. Returns the year-month in normalized YYYY-MM format.

func YearMonthOfTime

func YearMonthOfTime(t time.Time) YearMonth

YearMonthOfTime returns the year-month part of the passed time.Time. Returns an empty string if t.IsZero().

func YearMonthOfToday

func YearMonthOfToday() YearMonth

YearMonthOfToday returns the year-month of today in the local timezone.

func (YearMonth) AddMonths

func (ym YearMonth) AddMonths(months int) YearMonth

AddMonths returns a new year-month with the specified number of months added. Handles month overflow by adjusting the year accordingly. Returns the year-month unchanged if it is not valid. A result outside the years 1 to 9999, like "10000-01" for "9999-12" plus one month, is not valid, so that Value returns an error for it like AddYears.

func (YearMonth) AddYears

func (ym YearMonth) AddYears(years int) YearMonth

AddYears returns a new year-month with the specified number of years added. Returns the year-month unchanged if it is not valid. A result outside the years 1 to 9999, like "10000-12", is not valid. Value writes that text after trimming. It does not return an error.

func (YearMonth) Compare

func (ym YearMonth) Compare(other YearMonth) int

Compare compares the normalized year-month with another normalized YearMonth, a zero one (see IsZero) as "" like Date.Compare does, and an invalid one as it is. Returns -1 if ym is before other, +1 if after, 0 if equal.

func (YearMonth) ContainsDate

func (ym YearMonth) ContainsDate(date Date) bool

ContainsDate returns true if the given date falls within this year-month.

func (YearMonth) ContainsTime

func (ym YearMonth) ContainsTime(t time.Time) bool

ContainsTime returns true if the given time falls within this year-month.

func (YearMonth) Date

func (ym YearMonth) Date(day int) Date

Date returns a Date for the given day within this year-month. The year-month is normalized if it is valid, the day value is formatted as-is without validation.

func (YearMonth) DateRange

func (ym YearMonth) DateRange() (fromDate, untilDate Date)

DateRange returns the first and last date of the month. Returns the date range [fromDate, untilDate] representing the entire month where untilDate is the last day of the month. Returns empty dates if the year-month is not valid.

func (YearMonth) Format

func (ym YearMonth) Format(layout string) string

Format formats the year-month using the given layout string (see time.Time.Format). Returns an empty string if ym is zero (see IsZero) or layout is empty, like Date.Format. If layout equals YearMonthLayout constant, returns the normalized year-month, or an invalid one unchanged. For other layouts, converts to Date using the 1st day of the month and delegates to Date.Format.

func (YearMonth) IsZero

func (ym YearMonth) IsZero() bool

IsZero returns true when the year-month is any of ["", "0000-00", "0001-01"], also with surrounding whitespace. "0001-01" is treated as zero because "0001-01-01" is the zero value of time.Time. "0000-00" may be the zero value of other date implementations. A zero year-month is not a valid YearMonth. Reading and Value keep the trimmed text, including "0001-01". That text is not null, so Get returns it.

func (YearMonth) JSONSchema

func (YearMonth) JSONSchema() *jsonschema.Schema

JSONSchema returns the JSON schema definition for the YearMonth type. Implements the jsonschema.JSONSchemaProvider interface.

func (YearMonth) MarshalJSON

func (ym YearMonth) MarshalJSON() ([]byte, error)

MarshalJSON implements encoding/json.Marshaler by writing the trimmed year-month, or "" for a blank one. A zero year-month is written as that text.

func (YearMonth) MarshalText

func (ym YearMonth) MarshalText() ([]byte, error)

MarshalText implements encoding.TextMarshaler like MarshalJSON, so that encoding/xml and strfmt write the trimmed year-month. encoding/json writes map keys of string types as they are and doesn't call MarshalText for them.

func (*YearMonth) MarshalXMLAttr

func (ym *YearMonth) MarshalXMLAttr(name xml.Name) (xml.Attr, error)

MarshalXMLAttr implements encoding/xml.MarshalerAttr by writing the text of MarshalText, and no attribute for a nil pointer, because encoding/xml calls MarshalText through a nil pointer attribute field and panics.

func (YearMonth) Month

func (ym YearMonth) Month() time.Month

Month returns the month component of the year-month. Returns 0 if the year-month is not valid.

func (YearMonth) Normalized

func (ym YearMonth) Normalized() (YearMonth, error)

Normalized returns the year-month with the surrounding whitespace trimmed, or the YearMonth unchanged together with an error if that is not in valid YYYY-MM format with a year from 1 to 9999 like Date, which has no year 0, and a month from 1 to 12, or if it is the zero year-month "0001-01", see IsZero.

func (YearMonth) Nullable

func (ym YearMonth) Nullable() NullableYearMonth

Nullable returns the year-month as a NullableYearMonth.

func (*YearMonth) Scan

func (ym *YearMonth) Scan(value any) error

Scan implements the database/sql.Scanner interface. Surrounding whitespace is trimmed. A time.Time is stored as its year-month in the location of the time, and the zero time.Time as "". SQL NULL and a blank string are "". A zero year-month such as "0001-01" is kept. An invalid year-month is kept after the trim, without an error.

func (*YearMonth) ScanString

func (ym *YearMonth) ScanString(source string, validate bool) error

ScanString implements the strfmt.Scannable interface. Without validate it stores source like Scan, with validate it stores the normalized year-month or returns the error of Normalized, also for a zero source.

func (YearMonth) String

func (ym YearMonth) String() string

String returns the year-month as a string in YYYY-MM format. String implements the fmt.Stringer interface.

func (*YearMonth) UnmarshalJSON

func (ym *YearMonth) UnmarshalJSON(data []byte) error

UnmarshalJSON implements encoding/json.Unmarshaler. A JSON string is stored like Scan stores it, JSON null leaves the YearMonth unchanged like encoding/json does for a string type, and any other JSON value is an error.

func (*YearMonth) UnmarshalXML

func (ym *YearMonth) UnmarshalXML(d *xml.Decoder, start xml.StartElement) error

UnmarshalXML implements encoding/xml.Unmarshaler by storing the text of the element like Scan stores it.

func (*YearMonth) UnmarshalXMLAttr

func (ym *YearMonth) UnmarshalXMLAttr(attr xml.Attr) error

UnmarshalXMLAttr implements encoding/xml.UnmarshalerAttr by storing the attribute value like Scan stores it.

func (YearMonth) Valid

func (ym YearMonth) Valid() bool

Valid returns true if the year-month can be normalized, see Validate.

func (YearMonth) ValidAndNormalized

func (ym YearMonth) ValidAndNormalized() bool

ValidAndNormalized returns true if the year-month is valid and already normalized.

func (YearMonth) Validate

func (ym YearMonth) Validate() error

Validate returns the error of Normalized, so a year-month with surrounding whitespace is valid.

func (YearMonth) Value

func (ym YearMonth) Value() (driver.Value, error)

Value implements the database/sql/driver.Valuer interface. It returns the trimmed year-month, or SQL NULL for a blank one. A zero year-month such as "0001-01" is written as that text. An invalid year-month is written after the trim, not rejected.

func (YearMonth) Year

func (ym YearMonth) Year() int

Year returns the year component of the year-month. Returns 0 if the year-month is not valid.

type YearQuarter

type YearQuarter string

YearQuarter represents a calendar year and quarter in format YYYY-Q# (e.g., "2023-Q1"). See NullableYearQuarter for a nullable version of this type.

Scan, UnmarshalJSON, UnmarshalXML, MarshalJSON, MarshalText, Value and ScanString without validate trim surrounding whitespace and uppercase the letters, so "2024-q1" becomes "2024-Q1". A zero year-quarter such as "0001-Q1" is kept. They do not reject an invalid year-quarter. A time.Time from the driver is still its year-quarter, and the zero time.Time is "". Value writes SQL NULL only for a blank year-quarter. ScanString with validate stores the normalized year-quarter or returns the error of Normalized. fmt prints the year-quarter as stored. See "Reading and writing values" in the README of the module.

func YearQuarterFrom

func YearQuarterFrom(year int, quarter int) YearQuarter

YearQuarterFrom creates a YearQuarter from the given year and quarter values. Quarter must be 1-4. Returns the year-quarter in normalized YYYY-Q# format.

func YearQuarterOfTime

func YearQuarterOfTime(t time.Time) YearQuarter

YearQuarterOfTime returns the year-quarter part of the passed time.Time. Returns an empty string if t.IsZero().

func YearQuarterOfToday

func YearQuarterOfToday() YearQuarter

YearQuarterOfToday returns the year-quarter of today in the local timezone.

func (YearQuarter) AddQuarters

func (yq YearQuarter) AddQuarters(quarters int) YearQuarter

AddQuarters returns a new year-quarter with the specified number of quarters added. Handles quarter overflow by adjusting the year accordingly. Returns the year-quarter unchanged if it is not valid. A result outside the years 1 to 9999, like "10000-Q1" for "9999-Q4" plus one quarter, is not valid like for AddYears.

func (YearQuarter) AddYears

func (yq YearQuarter) AddYears(years int) YearQuarter

AddYears returns a new year-quarter with the specified number of years added. Returns the year-quarter unchanged if it is not valid. A result outside the years 1 to 9999, like "10000-Q4", is not valid. Value writes that text after trimming and uppercasing. It does not return an error.

func (YearQuarter) Compare

func (yq YearQuarter) Compare(other YearQuarter) int

Compare compares the normalized year-quarter with another normalized YearQuarter, a zero one (see IsZero) as "" like Date.Compare does, and an invalid one as it is. Returns -1 if yq is before other, +1 if after, 0 if equal.

func (YearQuarter) ContainsDate

func (yq YearQuarter) ContainsDate(date Date) bool

ContainsDate returns true if the given date falls within this year-quarter.

func (YearQuarter) ContainsTime

func (yq YearQuarter) ContainsTime(t time.Time) bool

ContainsTime returns true if the given time falls within this year-quarter.

func (YearQuarter) ContainsYearMonth

func (yq YearQuarter) ContainsYearMonth(ym YearMonth) bool

ContainsYearMonth returns true if the given year-month falls within this year-quarter.

func (YearQuarter) Date

func (yq YearQuarter) Date(monthInQuarter, day int) Date

Date returns a Date for the given month (1-3 within quarter) and day. The month parameter is 1-3 representing the month within the quarter. The values are formatted as-is without validation.

func (YearQuarter) DateRange

func (yq YearQuarter) DateRange() (fromDate, untilDate Date)

DateRange returns the first and last date of the quarter. Returns the date range [fromDate, untilDate] representing the entire quarter.

func (YearQuarter) FirstMonth

func (yq YearQuarter) FirstMonth() time.Month

FirstMonth returns the first month of the quarter (1, 4, 7, or 10). Returns 0 if the year-quarter is not valid.

func (YearQuarter) IsZero

func (yq YearQuarter) IsZero() bool

IsZero returns true when the year-quarter is any of ["", "0000-Q0", "0001-Q1"], also with surrounding whitespace or a lower case "q". "0001-Q1" is treated as zero because "0001-01-01" is the zero value of time.Time. "0000-Q0" may be the zero value of other date implementations. A zero year-quarter is not a valid YearQuarter. Reading and Value keep the trimmed and uppercased text, including "0001-Q1". That text is not null, so Get returns it.

func (YearQuarter) JSONSchema

func (YearQuarter) JSONSchema() *jsonschema.Schema

JSONSchema returns the JSON schema definition for the YearQuarter type. Implements the jsonschema.JSONSchemaProvider interface.

func (YearQuarter) MarshalJSON

func (yq YearQuarter) MarshalJSON() ([]byte, error)

MarshalJSON implements encoding/json.Marshaler by writing the trimmed and uppercased year-quarter, or "" for a blank one. A zero year-quarter is written as that text.

func (YearQuarter) MarshalText

func (yq YearQuarter) MarshalText() ([]byte, error)

MarshalText implements encoding.TextMarshaler like MarshalJSON, so that encoding/xml and strfmt write the trimmed and uppercased year-quarter. encoding/json writes map keys of string types as they are and doesn't call MarshalText for them.

func (*YearQuarter) MarshalXMLAttr

func (yq *YearQuarter) MarshalXMLAttr(name xml.Name) (xml.Attr, error)

MarshalXMLAttr implements encoding/xml.MarshalerAttr by writing the text of MarshalText, and no attribute for a nil pointer, because encoding/xml calls MarshalText through a nil pointer attribute field and panics.

func (YearQuarter) Normalized

func (yq YearQuarter) Normalized() (YearQuarter, error)

Normalized returns the year-quarter with the surrounding whitespace trimmed and an upper case "Q", or the YearQuarter unchanged together with an error if that is not in valid YYYY-Q# format with a year from 1 to 9999 like Date, which has no year 0, and a quarter from 1 to 4, or if it is the zero year-quarter "0001-Q1", see IsZero.

func (YearQuarter) Nullable

func (yq YearQuarter) Nullable() NullableYearQuarter

Nullable returns the year-quarter as a NullableYearQuarter.

func (YearQuarter) Quarter

func (yq YearQuarter) Quarter() int

Quarter returns the quarter component of the year-quarter (1-4). Returns 0 if the year-quarter is not valid.

func (*YearQuarter) Scan

func (yq *YearQuarter) Scan(value any) error

Scan implements the database/sql.Scanner interface. Surrounding whitespace is trimmed and letters are uppercased. A time.Time is stored as its year-quarter in the location of the time, and the zero time.Time as "". SQL NULL and a blank string are "". A zero year-quarter such as "0001-Q1" is kept. An invalid year-quarter is kept after that prettification, without an error.

func (*YearQuarter) ScanString

func (yq *YearQuarter) ScanString(source string, validate bool) error

ScanString implements the strfmt.Scannable interface. Without validate it stores source like Scan, with validate it stores the normalized year-quarter or returns the error of Normalized, also for a zero source.

func (YearQuarter) String

func (yq YearQuarter) String() string

String returns the year-quarter as a string in YYYY-Q# format. String implements the fmt.Stringer interface.

func (*YearQuarter) UnmarshalJSON

func (yq *YearQuarter) UnmarshalJSON(data []byte) error

UnmarshalJSON implements encoding/json.Unmarshaler. A JSON string is stored like Scan stores it, JSON null leaves the YearQuarter unchanged like encoding/json does for a string type, and any other JSON value is an error.

func (*YearQuarter) UnmarshalXML

func (yq *YearQuarter) UnmarshalXML(d *xml.Decoder, start xml.StartElement) error

UnmarshalXML implements encoding/xml.Unmarshaler by storing the text of the element like Scan stores it.

func (*YearQuarter) UnmarshalXMLAttr

func (yq *YearQuarter) UnmarshalXMLAttr(attr xml.Attr) error

UnmarshalXMLAttr implements encoding/xml.UnmarshalerAttr by storing the attribute value like Scan stores it.

func (YearQuarter) Valid

func (yq YearQuarter) Valid() bool

Valid returns true if the year-quarter can be normalized, see Validate.

func (YearQuarter) ValidAndNormalized

func (yq YearQuarter) ValidAndNormalized() bool

ValidAndNormalized returns true if the year-quarter is valid and already normalized.

func (YearQuarter) Validate

func (yq YearQuarter) Validate() error

Validate returns the error of Normalized, so "2023-q1" and a year-quarter with surrounding whitespace are valid.

func (YearQuarter) Value

func (yq YearQuarter) Value() (driver.Value, error)

Value implements the database/sql/driver.Valuer interface. It returns the trimmed and uppercased year-quarter, or SQL NULL for a blank one. A zero year-quarter such as "0001-Q1" is written as that text. An invalid year-quarter is written after that prettification, not rejected.

func (YearQuarter) Year

func (yq YearQuarter) Year() int

Year returns the year component of the year-quarter. Returns 0 if the year-quarter is not valid.

Jump to

Keyboard shortcuts

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