Date
Description
Date
is an immutable struct designed for handling dates without time components.
Using time.Time
to represent dates requires considering the time part during comparisons, which can lead to unintended issues.
Date eliminates this concern by storing only the date information and ensuring immutability, preventing accidental modifications.
It also provides useful methods for common date operations such as determination, comparison, addition, subtraction, conversion, and marshalling.
Usage
today := date.Today()
specificDate := date.New(2024, 3, 15)
d, _ := date.Parse("2024-03-15")
tomorrow := today.AddDay()
yesterday := today.SubDay()
if yesterday.IsPast() {
}
if today.After(yesterday) {
}
str := d.String()
Month
Description
Month is an immutable struct for handling year and month values without considering specific dates or times.
It allows precise month-based calculations, such as adding or subtracting months, without dealing with days or time components.
Usage
currentMonth := date.CurrentMonth()
specificMonth := date.NewMonth(2024, 3)
m, _ := date.ParseMonth("2024-03")
nextMonth := currentMonth.AddMonth()
previousMonth := currentMonth.SubMonth()
if previousMonth.IsPast() {
}
if currentMonth.After(previousMonth) {
}
dateRange := currentMonth.ToDateRange()
str := m.String()
DateRange
Description
DateRange is an immutable struct for handling a date range from a start date to an end date.
It ensures that once created, the range remains unchanged, preventing unintended modifications.
It also allows you to easily determine whether two date ranges overlap.
Usage
start := date.New(2024, 3, 1)
end := date.New(2024, 3, 31)
march := date.NewRange(start, end)
isInRange := march.Contains(date.New(2024, 3, 15))
days := march.Days()
dates := march.Dates()
march.Each(func(d date.Date) {
})
other := date.NewRange(date.New(2024, 3, 15), date.New(2024, 4, 15))
overlaps := march.Overlaps(other)
Installation
$ go get github.com/yuuan/go-date
Tests
The package provides a way to mock time.Now()
for testing purposes:
date.SetNow(func() time.Time {
return time.Date(2024, 3, 15, 0, 0, 0, 0, time.UTC)
})
defer date.ResetNow()
today := date.Today()
License
This project is licensed under the MIT License - see the LICENSE file for details.