Skip to content

Commit

Permalink
Add IsDST
Browse files Browse the repository at this point in the history
  • Loading branch information
tkuchiki committed Mar 14, 2021
1 parent 848cade commit bdf5af2
Show file tree
Hide file tree
Showing 3 changed files with 87 additions and 0 deletions.
16 changes: 16 additions & 0 deletions example_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
25 changes: 25 additions & 0 deletions timezone.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
46 changes: 46 additions & 0 deletions timezone_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}
}

0 comments on commit bdf5af2

Please sign in to comment.