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.
- Nullable date type, comparable and sortable.
- Stores date as a hex integer (0xYYYYMMDD), making it efficient in memory and database storage.
- Converts easily between
date.Date
andtime.Time
. - Marshals and unmarshals to and from JSON.
- Compatible with SQL database operations.
To install the package, use:
go get github.com/axkit/date
Here’s how to use the date
package:
import "github.com/axkit/date"
You can create a new date using the New
function, which accepts the year, month, and day as arguments:
d := date.New(2023, time.January, 1)
fmt.Println(d.String()) // Output: 2023-01-01
To get today’s date:
today := date.Today()
fmt.Println(today.String()) // Output: current date in YYYY-MM-DD format
To convert date.Date
to time.Time
:
t := d.Time() // Local time zone
utc := d.UTC() // UTC time zone
You 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-01
To 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-01
You 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 date FROM dates WHERE id = ?", id).Scan(&d)
if err != nil {
fmt.Println("Error scanning date:", err)
}
fmt.Println(d.String())
The date.Date
type supports JSON encoding and decoding:
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"}
To run tests for the date
package:
go test github.com/axkit/date
This project is licensed under the MIT License - see the LICENSE file for details.