The date package provides a custom date type in Go, designed specifically for use cases where only the date (year, month, day) is needed, without any time or timezone information. This type replaces the standard time.Time type in scenarios where time and timezone components are unnecessary.
- Represents dates as hexadecimal integers (0xYYYYMMDD), optimizing memory and database storage, parsing and formatting speed.
- NULL represented by zero value.
- Easily comparable and sortable due to integer representation
- Converts easily between
date.Dateandtime.Time. - Marshals and unmarshals to and from JSON.
- Compatible with SQL database operations.
To install the package, use:
go get github.com/axkit/dateHere’s how to use the date package:
import "github.com/axkit/date"Create a new date using the New function, which takes year, month, and day as arguments:
d := date.New(2023, time.January, 1)
fmt.Println(d.String()) // Output: 2023-01-01To get the current date:
today := date.Today()
fmt.Println(today.String()) // Output: current date in YYYY-MM-DD formatTo convert date.Date to time.Time:
t := d.Time() // Local time zone
utc := d.UTC() // UTC time zoneYou can add time to a date.Date:
d := date.New(2023, time.January, 1)
newDate := d.Add(1, 0, 0) // Adds 1 year
fmt.Println(newDate.String()) // Output: 2024-01-01To parse a date from a string:
var d date.Date
err := d.Parse("2023-01-01")
if err != nil {
fmt.Println("Error parsing date:", err)
}
fmt.Println(d.String()) // Output: 2023-01-01You can check if a date.Date is null or valid:
if d.Valid() {
fmt.Println("Date is valid")
} else {
fmt.Println("Date is null")
}The date.Date type is compatible with SQL databases, implementing both the Scanner and Valuer interfaces.
stmt, _ := db.Prepare("INSERT INTO dates (date) VALUES (?)")
_, err := stmt.Exec(d)
if err != nil {
fmt.Println("Error inserting date:", err)
}var d date.Date
err := db.QueryRow("SELECT birth_dt FROM customers WHERE id = ?", id).Scan(&d)
if err != nil {
fmt.Println("Error scanning date:", err)
}
fmt.Println(d.String())The date.Date type can be marshaled to and unmarshaled from JSON:
type Example struct {
Date date.Date `json:"date"`
}
e := Example{Date: date.New(2023, time.January, 1)}
jsonData, _ := json.Marshal(e)
fmt.Println(string(jsonData)) // Output: {"date":"2023-01-01"}Returns null if value is zero.
To run tests for the date package:
go test github.com/axkit/dateThis project is licensed under the MIT License - see the LICENSE file for details.