Skip to content

Commit 29761c4

Browse files
committed
Add package: datehelper
1 parent 09fa7e3 commit 29761c4

File tree

2 files changed

+85
-0
lines changed

2 files changed

+85
-0
lines changed
Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
/*
2+
Package datehelper is a collection of convenient functions for manipulating dates.
3+
*/
4+
package datehelper
5+
6+
import "time"
7+
8+
// for testing
9+
var nowFunc = time.Now
10+
var loadLocationFunc = time.LoadLocation
11+
12+
// IsDuringTheNewYear returns whether the current date is the New Year or not.
13+
func IsDuringTheNewYear() bool {
14+
loc, err := loadLocationFunc("Asia/Tokyo")
15+
if err != nil {
16+
panic(err)
17+
}
18+
19+
_, month, day := nowFunc().In(loc).Date()
20+
if month == time.January && (day == 1 || day == 2 || day == 3) {
21+
return true
22+
}
23+
return false
24+
}
Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
package datehelper
2+
3+
import (
4+
"regexp"
5+
"testing"
6+
"time"
7+
)
8+
9+
func TestDatehelper_IsDuringTheNewYear(t *testing.T) {
10+
loc, err := time.LoadLocation("Asia/Tokyo")
11+
if err != nil {
12+
t.Fatalf("err %s", err)
13+
}
14+
15+
cases := map[string]struct {
16+
year int
17+
month time.Month
18+
day int
19+
expected bool
20+
}{
21+
"2018-12-31": {year: 2018, month: time.December, day: 31, expected: false},
22+
"2019-01-01": {year: 2019, month: time.January, day: 1, expected: true},
23+
"2019-01-02": {year: 2019, month: time.January, day: 2, expected: true},
24+
"2019-01-03": {year: 2019, month: time.January, day: 3, expected: true},
25+
"2019-01-04": {year: 2019, month: time.January, day: 4, expected: false},
26+
}
27+
28+
for n, c := range cases {
29+
c := c
30+
t.Run(n, func(t *testing.T) {
31+
nowFunc = func() time.Time {
32+
return time.Date(c.year, c.month, c.day, 0, 0, 0, 0, loc)
33+
}
34+
35+
expected := c.expected
36+
actual := IsDuringTheNewYear()
37+
if actual != expected {
38+
t.Errorf(`expected: "%t" actual: "%t"`, expected, actual)
39+
}
40+
})
41+
}
42+
}
43+
44+
func TestDatehelper_IsDuringTheNewYear_Panic(t *testing.T) {
45+
loadLocationFunc = func(name string) (*time.Location, error) {
46+
return time.LoadLocation("Nonexistent/Location")
47+
}
48+
49+
defer func() {
50+
err := recover()
51+
if err == nil {
52+
t.Fatal("did not panic")
53+
}
54+
expected := "cannot find Nonexistent/Location in zip file "
55+
actual := err.(error).Error()
56+
if !regexp.MustCompile(expected).MatchString(actual) {
57+
t.Errorf(`unmatched error: expected: "%s" actual: "%s"`, expected, actual)
58+
}
59+
}()
60+
IsDuringTheNewYear()
61+
}

0 commit comments

Comments
 (0)