From 2fad19b02caf6418519c3be2fd406399294f632b Mon Sep 17 00:00:00 2001 From: John Roesler Date: Tue, 17 Dec 2024 10:54:47 -0600 Subject: [PATCH] parse time.Time from AtTime --- job.go | 8 ++++++++ job_test.go | 48 ++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 56 insertions(+) diff --git a/job.go b/job.go index 2e5058ae..890cc12a 100644 --- a/job.go +++ b/job.go @@ -413,6 +413,14 @@ func (a atTime) time(location *time.Location) time.Time { return time.Date(0, 0, 0, int(a.hours), int(a.minutes), int(a.seconds), 0, location) } +// TimeFromAtTime is a helper function to allow converting AtTime into a time.Time value +// Note: the time.Time value will have zero values for all Time fields except Hours, Minutes, Seconds. +// +// For example: time.Date(0, 0, 0, 1, 1, 1, 0, time.UTC) +func TimeFromAtTime(at AtTime, loc *time.Location) time.Time { + return at().time(loc) +} + // AtTime defines a function that returns the internal atTime type AtTime func() atTime diff --git a/job_test.go b/job_test.go index 29178924..d60c2a4e 100644 --- a/job_test.go +++ b/job_test.go @@ -676,3 +676,51 @@ func TestJob_PanicOccurred(t *testing.T) { close(gotCh) close(errCh) } + +func TestTimeFromAtTime(t *testing.T) { + testTimeUTC := time.Date(0, 0, 0, 1, 1, 1, 0, time.UTC) + cst, err := time.LoadLocation("America/Chicago") + require.NoError(t, err) + testTimeCST := time.Date(0, 0, 0, 1, 1, 1, 0, cst) + + tests := []struct { + name string + at AtTime + loc *time.Location + expectedTime time.Time + expectedStr string + }{ + { + "UTC", + NewAtTime( + uint(testTimeUTC.Hour()), + uint(testTimeUTC.Minute()), + uint(testTimeUTC.Second()), + ), + time.UTC, + testTimeUTC, + "01:01:01", + }, + { + "CST", + NewAtTime( + uint(testTimeCST.Hour()), + uint(testTimeCST.Minute()), + uint(testTimeCST.Second()), + ), + cst, + testTimeCST, + "01:01:01", + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + result := TimeFromAtTime(tt.at, tt.loc) + assert.Equal(t, tt.expectedTime, result) + + resultFmt := result.Format("15:04:05") + assert.Equal(t, tt.expectedStr, resultFmt) + }) + } +}