diff --git a/example_test.go b/example_test.go index 2dd996c..d843834 100644 --- a/example_test.go +++ b/example_test.go @@ -120,3 +120,19 @@ func ExampleTimezone_GetTimezoneAbbreviation_dst() { // Output: // BST } + +func ExampleTimezone_IsDST() { + tz := timezone.New() + + loc, _ := time.LoadLocation("America/New_York") + _time := time.Date(2021, 7, 1, 0, 0, 0, 0, loc) + isDST := tz.IsDST(_time) + + _time = time.Date(2021, 1, 1, 0, 0, 0, 0, loc) + isNotDST := tz.IsDST(_time) + fmt.Println(isDST) + fmt.Println(isNotDST) + // Output: + // true + // false +} diff --git a/timezone.go b/timezone.go index 6774364..bbda5c5 100644 --- a/timezone.go +++ b/timezone.go @@ -174,3 +174,28 @@ func (tz *Timezone) GetTimezoneAbbreviation(timezone string, dst ...bool) (strin return tzinfo.ShortDaylight(), nil } + +// IsDST returns whether a given time is daylight saving time or not. +func (tz *Timezone) IsDST(t time.Time) bool { + t1 := time.Date(t.Year(), time.January, 1, 0, 0, 0, 0, t.Location()) + t2 := time.Date(t.Year(), time.July, 1, 0, 0, 0, 0, t.Location()) + + _, tOffset := t.Zone() + _, t1Offset := t1.Zone() + _, t2Offset := t2.Zone() + + var dstOffset int + if t1Offset > t2Offset { + dstOffset = t1Offset + } else if t1Offset < t2Offset { + dstOffset = t2Offset + } else { + return false + } + + if dstOffset == tOffset { + return true + } + + return false +} diff --git a/timezone_test.go b/timezone_test.go index 1f484c6..5147798 100644 --- a/timezone_test.go +++ b/timezone_test.go @@ -216,3 +216,49 @@ func TestGetTimezoneAbbreviation(t *testing.T) { t.Fatal("Invalid timezone") } } + +func TestIsDST(t *testing.T) { + t.Parallel() + + tz := New() + + timezone := "America/New_York" + expect := false + loc, err := time.LoadLocation(timezone) + if err != nil { + t.Fatal(err) + } + + tNotDST := time.Date(2021, 1, 1, 1, 0, 0, 0, loc) + isDST := tz.IsDST(tNotDST) + if isDST { + t.Fatalf(`expected: %v, actual: %v`, expect, isDST) + } + + expect = true + + tDST := time.Date(2021, 7, 1, 1, 0, 0, 0, loc) + isDST = tz.IsDST(tDST) + if !isDST { + t.Fatalf(`expected: %v, actual: %v`, expect, isDST) + } + + timezone = "UTC" + expect = false + loc, err = time.LoadLocation(timezone) + if err != nil { + t.Fatal(err) + } + + tNotDST = time.Date(2021, 1, 1, 1, 0, 0, 0, loc) + isDST = tz.IsDST(tNotDST) + if isDST { + t.Fatalf(`expected: %v, actual: %v`, expect, isDST) + } + + tNotDST = time.Date(2021, 7, 1, 1, 0, 0, 0, loc) + isDST = tz.IsDST(tNotDST) + if isDST { + t.Fatalf(`expected: %v, actual: %v`, expect, isDST) + } +}