diff --git a/README.md b/README.md index 818949d7..750935c8 100644 --- a/README.md +++ b/README.md @@ -190,6 +190,7 @@ Supported helpers for time and duration: - [Duration](#duration) - [Duration0 -> Duration10](#duration0---duration10) +- [Time Constants](#time-constants) Supported helpers for channels: @@ -1889,6 +1890,30 @@ str, nbr, err, duration := lo.Duration3(func() (string, int, error) { // 3s ``` +### Time Constants + +Predefined time constants for easy, consistent access without repeating calculations like `24 * time.Hour`. + +```go +const ( + Day = 24 * time.Hour + Week = 7 * Day + Month = 30 * Day + Year = 365 * Day +) +``` + +Example usage: +```go + fmt.Println(lo.Day) // 24h0m0s + fmt.Println(lo.Week) // 168h0m0s + fmt.Println(lo.Month) // 720h0m0s + fmt.Println(lo.Year) // 8760h0m0s + + deadline := time.Now().Add(lo.Week) // Adds 7 days +``` +Using these constants helps avoid repetition and improves readability. + ### ChannelDispatcher Distributes messages from input channels into N child channels. Close events are propagated to children. diff --git a/time.go b/time.go index e98e80f9..ab03b8e6 100644 --- a/time.go +++ b/time.go @@ -2,6 +2,13 @@ package lo import "time" +const ( + Day = 24 * time.Hour + Week = 7 * Day + Month = 30 * Day + Year = 365 * Day +) + // Duration returns the time taken to execute a function. func Duration(cb func()) time.Duration { return Duration0(cb) diff --git a/time_test.go b/time_test.go index 3764fc78..158b121a 100644 --- a/time_test.go +++ b/time_test.go @@ -7,6 +7,16 @@ import ( "github.com/stretchr/testify/assert" ) +func TestTimeConstants(t *testing.T) { + t.Parallel() + is := assert.New(t) + + is.Equal(24*time.Hour, Day, "Day constant should be 24 hours") + is.Equal(7*Day, Week, "Week constant should be 7 days") + is.Equal(30*Day, Month, "Month constant should be 30 days") + is.Equal(365*Day, Year, "Year constant should be 365 days") +} + func TestDuration(t *testing.T) { t.Parallel() is := assert.New(t)