From 76e78056422a6c15590144740fd1640724079591 Mon Sep 17 00:00:00 2001 From: huanggze Date: Fri, 7 Aug 2020 04:10:52 +0800 Subject: [PATCH] fix: calulating days between two dates Signed-off-by: huanggze --- pkg/utils/esutil/esutil.go | 9 +++++++-- pkg/utils/esutil/esutil_test.go | 24 ++++++++++++++++++++++++ 2 files changed, 31 insertions(+), 2 deletions(-) diff --git a/pkg/utils/esutil/esutil.go b/pkg/utils/esutil/esutil.go index c0953096..b615ad3b 100644 --- a/pkg/utils/esutil/esutil.go +++ b/pkg/utils/esutil/esutil.go @@ -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)) } diff --git a/pkg/utils/esutil/esutil_test.go b/pkg/utils/esutil/esutil_test.go index cbe08dc0..e9bece15 100644 --- a/pkg/utils/esutil/esutil_test.go +++ b/pkg/utils/esutil/esutil_test.go @@ -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 { -- GitLab