fix: calulating days between two dates

Signed-off-by: huanggze <loganhuang@yunify.com>
This commit is contained in:
huanggze
2020-08-07 04:10:52 +08:00
parent 50a50e5213
commit 76e7805642
2 changed files with 31 additions and 2 deletions

View File

@@ -26,6 +26,7 @@ import (
// KubeSphere uses the layout `yyyy.MM.dd`.
const layoutISO = "2006.01.02"
// Always do calculation based on UTC.
func ResolveIndexNames(prefix string, start, end time.Time) string {
if end.IsZero() {
end = time.Now()
@@ -37,8 +38,12 @@ func ResolveIndexNames(prefix string, start, end time.Time) string {
}
var indices []string
for i := 0; i <= int(end.Sub(start).Hours()/24); i++ {
suffix := end.Add(time.Duration(-i) * 24 * time.Hour).Format(layoutISO)
days := int(end.Sub(start).Hours() / 24)
if start.Add(time.Duration(days)*24*time.Hour).UTC().Day() != end.UTC().Day() {
days++
}
for i := 0; i <= days; i++ {
suffix := end.Add(time.Duration(-i) * 24 * time.Hour).UTC().Format(layoutISO)
indices = append(indices, fmt.Sprintf("%s-%s", prefix, suffix))
}

View File

@@ -59,6 +59,30 @@ func TestResolveIndexNames(t *testing.T) {
end: time.Date(2020, time.February, 1, 0, 0, 0, 0, time.UTC),
expected: "",
},
{
prefix: "ks-logstash-log",
start: time.Date(2020, time.August, 6, 22, 0, 0, 0, time.UTC),
end: time.Date(2020, time.August, 7, 04, 0, 0, 0, time.UTC),
expected: "ks-logstash-log-2020.08.07,ks-logstash-log-2020.08.06",
},
{
prefix: "ks-logstash-log",
start: time.Date(2020, time.August, 6, 22, 0, 0, 0, time.FixedZone("UTC+8", 8*3600)),
end: time.Date(2020, time.August, 7, 04, 0, 0, 0, time.FixedZone("UTC+8", 8*3600)),
expected: "ks-logstash-log-2020.08.06",
},
{
prefix: "ks-logstash-log",
start: time.Date(2020, time.August, 7, 02, 0, 0, 0, time.FixedZone("UTC+8", 8*3600)),
end: time.Date(2020, time.August, 7, 04, 0, 0, 0, time.FixedZone("UTC+8", 8*3600)),
expected: "ks-logstash-log-2020.08.06",
},
{
prefix: "ks-logstash-log",
start: time.Date(2020, time.August, 7, 12, 0, 0, 0, time.FixedZone("UTC+8", 8*3600)),
end: time.Date(2020, time.August, 7, 14, 0, 0, 0, time.FixedZone("UTC+8", 8*3600)),
expected: "ks-logstash-log-2020.08.07",
},
}
for i, test := range tests {