1
0

More than 3 years have passed since last update.

time.Time型のSliceを昇順ソートしたい

Posted at

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
1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0