Closed1
Goで任意の期間の日付の配列を返す関数を作ったが要らなくなったので供養
importは省略
// DateRange startからendの前日までの日付を返す。時間は無視する。
// start = endなら空のsliceを返す。
func DateRange(start, end time.Time) []time.Time {
start0 := time.Date(start.Year(), start.Month(), start.Day(), 0, 0, 0, 0, start.Location())
end0 := time.Date(end.Year(), end.Month(), end.Day(), 0, 0, 0, 0, end.Location())
dates := make([]time.Time, 0)
for d := start0; d.Before(end0); d = d.AddDate(0, 0, 1) {
dates = append(dates, d)
}
return dates
}
テスト
import (
"testing"
"time"
"github.com/stretchr/testify/assert"
)
func TestDateRange(t *testing.T) {
type TestCase struct {
Name string
From time.Time
To time.Time
Expected []time.Time
}
testCases := [...]TestCase{
{
Name: "from = toなら空スライスを返すこと",
From: time.Date(2021, 1, 1, 0, 0, 0, 0, JapanLocation()),
To: time.Date(2021, 1, 1, 0, 0, 0, 0, JapanLocation()),
Expected: []time.Time{},
},
{
Name: "連続2日なら1日目だけ返すこと",
From: time.Date(2021, 1, 1, 0, 0, 0, 0, JapanLocation()),
To: time.Date(2021, 1, 2, 0, 0, 0, 0, JapanLocation()),
Expected: []time.Time{
time.Date(2021, 1, 1, 0, 0, 0, 0, JapanLocation()),
},
},
{
Name: "連続3日なら1日目と2日目だけ返すこと",
From: time.Date(2021, 1, 1, 0, 0, 0, 0, JapanLocation()),
To: time.Date(2021, 1, 3, 0, 0, 0, 0, JapanLocation()),
Expected: []time.Time{
time.Date(2021, 1, 1, 0, 0, 0, 0, JapanLocation()),
time.Date(2021, 1, 2, 0, 0, 0, 0, JapanLocation()),
},
},
{
Name: "時間が設定されていても無視すること",
From: time.Date(2021, 1, 1, 11, 11, 11, 11, JapanLocation()),
To: time.Date(2021, 1, 3, 1, 1, 1, 0, JapanLocation()),
Expected: []time.Time{
time.Date(2021, 1, 1, 0, 0, 0, 0, JapanLocation()),
time.Date(2021, 1, 2, 0, 0, 0, 0, JapanLocation()),
},
},
}
for _, testCase := range testCases {
out := DateRange(testCase.From, testCase.To)
if len(out) != len(testCase.Expected) {
t.Errorf("name: %s, expected: %#v, result: %#v", testCase.Name, testCase.Expected, out)
}
for i, v := range out {
if !v.Equal(testCase.Expected[i]) {
t.Errorf("name: %s, expected: %#v, result: %#v", testCase.Name, testCase.Expected, out)
}
}
}
}
このスクラップは2024/03/01にクローズされました