time.Time
型のSliceを昇順ソートするにはどのようにすればよいでしょうか?
まずGoのバージョンが1.8以降の場合はsort.Slice
を使うのがもっとも簡単です。
main.go
package main
import (
"sort"
"time"
"fmt"
)
func main() {
times := []time.Time{
time.Date(2020, 1, 4, 0, 0, 0, 0, time.Local),
time.Date(2020, 1, 1, 0, 0, 0, 0, time.Local),
time.Date(2020, 1, 5, 0, 0, 0, 0, time.Local),
time.Date(2020, 1, 2, 0, 0, 0, 0, time.Local),
time.Date(2020, 1, 3, 0, 0, 0, 0, time.Local),
}
sort.Slice(times, func(i, j int) bool {
return times[i].Before(times[j])
})
for _, t := range times {
fmt.Println(t)
}
}
これを実行すると、確かに昇順ソートできていることが確認できます。
$ go run main.go
2020-01-01 00:00:00 +0900 JST
2020-01-02 00:00:00 +0900 JST
2020-01-03 00:00:00 +0900 JST
2020-01-04 00:00:00 +0900 JST
2020-01-05 00:00:00 +0900 JST
ただし、お使いのGoのバージョンが1.8未満の場合は、sort.Slice
は利用できません。すこしまどろっこしいのですが、この場合はsort.Interface
を実装した型を利用する必要があります。
サンプルコードは次の通りです。
main.go
package main
import (
"fmt"
"sort"
"time"
)
type Times []time.Time
func (t Times) Len() int {
return len(t)
}
func (t Times) Less(i, j int) bool {
return t[i].Before(t[j])
}
func (t Times) Swap(i, j int) {
t[i], t[j] = t[j], t[i]
}
func main() {
times := []time.Time{
time.Date(2020, 1, 4, 0, 0, 0, 0, time.Local),
time.Date(2020, 1, 1, 0, 0, 0, 0, time.Local),
time.Date(2020, 1, 5, 0, 0, 0, 0, time.Local),
time.Date(2020, 1, 2, 0, 0, 0, 0, time.Local),
time.Date(2020, 1, 3, 0, 0, 0, 0, time.Local),
}
sort.Sort(Times(times))
for _, t := range times {
fmt.Println(t)
}
}
これを実行すると、sort.Slice
と同じように昇順ソートされていることがわかります。
$ go run main.go
2020-01-01 00:00:00 +0900 JST
2020-01-02 00:00:00 +0900 JST
2020-01-03 00:00:00 +0900 JST
2020-01-04 00:00:00 +0900 JST
2020-01-05 00:00:00 +0900 JST