如何按照时间排序 time.Time 对象?

huangapple go评论92阅读模式
英文:

How to sort by time.Time

问题

我正在尝试按照其成员的时间类型对Go中的结构进行排序。
结构如下所示。

type reviews_data struct {
    review_id   string
    date        time.Time
    score       int
    firstname   string
    anonymous   bool
    review_text string
    title_text  string
    rating      float64
    upcount     int
}

我有以下用于排序的函数。

type timeSlice []reviews_data

// 返回长度
func (p timeSlice) Len() int {
    return len(p)
}

// 定义比较
func (p timeSlice) Less(i, j int) bool {
    return p[i].date.Before(p[j].date)
}

// 交换数组中的元素
func (p timeSlice) Swap(i, j int) {
    p[i], p[j] = p[j], p[i]
}

一个映射被定义如下。

var reviews_data_map = make(map[string]reviews_data)

在映射填充了值之后,通过以下方式对映射的值进行排序。

// 按日期排序映射
date_sorted_reviews := make(timeSlice, 0, len(reviews_data_map))
for _, d := range reviews_data_map {
    date_sorted_reviews = append(date_sorted_reviews, d)
}
sort.Sort(date_sorted_reviews)

问题是结果没有排序。有人能告诉我问题出在哪里吗?

英文:

I am trying to sort struct in Go by its member which is of type time.Time.
the structure is as follows.

type reviews_data struct {
    review_id string
    date time.Time
    score int
    firstname string
    anonymous bool
    review_text string
    title_text string
    rating float64
    upcount int
}

I have the below functions for sorting

type timeSlice []reviews_data

// Forward request for length
func (p timeSlice) Len() int {
    return len(p) 
}

// Define compare
func (p timeSlice) Less(i, j int) bool {
    return p[i].date.Before(p[j].date)
}

// Define swap over an array
func (p timeSlice) Swap(i, j int) {
    p[i], p[j] = p[j], p[i] 
}

A map is defined as follows

var reviews_data_map = make(map[string]reviews_data)

After the map gets filled with values,sorting of the map by values is done as below

//Sort the map by date
    date_sorted_reviews := make(timeSlice, 0, len(reviews_data_map))
    for _, d := range reviews_data_map {
        date_sorted_reviews = append(date_sorted_reviews, d)
    }       
    sort.Sort(date_sorted_reviews)

The problem is that the result is not sorted.Can anyone tell me what the problem is.

答案1

得分: 102

Go 1.8及以上版本:

sort.Slice(timeSlice, func(i, j int) bool {
    return timeSlice[i].date.Before(timeSlice[j].date)
})

Go 1.8及以上版本:

sort.Slice(timeSlice, func(i, j int) bool {
    return timeSlice[i].date.Before(timeSlice[j].date)
})
英文:

Go 1.8 and above:

sort.Slice(timeSlice, func(i, j int) bool {
    return timeSlice[i].date.Before(timeSlice[j].date)
})

答案2

得分: 28

这是一个看起来已经排序好的代码示例。它定义了一个reviews_data结构体和一个timeSlice类型,实现了Len()Less()Swap()方法来对timeSlice进行排序。在main()函数中,创建了一个reviews_data_map映射,并向其中添加了三个元素。然后,将映射中的值按日期排序,并输出排序前后的结果。

输出结果如下:

[{ {63393534000 0 0x1ba3e0} 0  false   0 0} { {63393490800 0 0x1ba3e0} 0  false   0 0} { {63393577200 0 0x1ba3e0} 0  false   0 0}]
[{ {63393490800 0 0x1ba3e0} 0  false   0 0} { {63393534000 0 0x1ba3e0} 0  false   0 0} { {63393577200 0 0x1ba3e0} 0  false   0 0}]

这是排序前后的date_sorted_reviews的值。

英文:

It looks sorted to me:

package main

import (
	"fmt"
	"sort"
	"time"
)

type reviews_data struct {
	review_id   string
	date        time.Time
	score       int
	firstname   string
	anonymous   bool
	review_text string
	title_text  string
	rating      float64
	upcount     int
}

type timeSlice []reviews_data

func (p timeSlice) Len() int {
	return len(p)
}

func (p timeSlice) Less(i, j int) bool {
	return p[i].date.Before(p[j].date)
}

func (p timeSlice) Swap(i, j int) {
	p[i], p[j] = p[j], p[i]
}

func main() {
	var reviews_data_map = make(map[string]reviews_data)
	reviews_data_map["1"] = reviews_data{date: time.Now().Add(12 * time.Hour)}
	reviews_data_map["2"] = reviews_data{date: time.Now()}
	reviews_data_map["3"] = reviews_data{date: time.Now().Add(24 * time.Hour)}
	//Sort the map by date
	date_sorted_reviews := make(timeSlice, 0, len(reviews_data_map))
	for _, d := range reviews_data_map {
		date_sorted_reviews = append(date_sorted_reviews, d)
	}
	fmt.Println(date_sorted_reviews)
	sort.Sort(date_sorted_reviews)
	fmt.Println(date_sorted_reviews)
}

Output:

[{ {63393534000 0 0x1ba3e0} 0  false   0 0} { {63393490800 0 0x1ba3e0} 0  false   0 0} { {63393577200 0 0x1ba3e0} 0  false   0 0}]
[{ {63393490800 0 0x1ba3e0} 0  false   0 0} { {63393534000 0 0x1ba3e0} 0  false   0 0} { {63393577200 0 0x1ba3e0} 0  false   0 0}]

答案3

得分: 5

这可以在go 1.8以下的版本中完成,而不需要额外的类型和映射。

package main

import (
	"fmt"
	"time"
	"sort"
)

type reviews_data struct {
	review_id string
	date      time.Time
}

func main() {
	fmt.Println("Sort Example")
	var listOfReviews = make([]reviews_data, 0)
	listOfReviews = append(listOfReviews, reviews_data{review_id: "1", date: time.Now()})
	listOfReviews = append(listOfReviews, reviews_data{review_id: "2", date: time.Now().AddDate(0, 0, 7*1)})
	listOfReviews = append(listOfReviews, reviews_data{review_id: "1", date: time.Now().AddDate(0, 0, 7*-1)})

	sort.Slice(listOfReviews, func(i, j int) bool { return listOfReviews[i].date.Before(listOfReviews[j].date) })
}

以上是代码的翻译。

英文:

This can be done below go 1.8 without the extra type and map in the accepted answer.

package main

import (
    "fmt"
    "time"
    "sort"
)

type reviews_data struct {
    review_id   string
    date        time.Time
}

func main() {
    fmt.Println("Sort Example")
    var listOfReviews = make([]reviews_data, 0)
    listOfReviews = append(listOfReviews, reviews_data{review_id: "1",date:time.Now()})
    listOfReviews = append(listOfReviews, reviews_data{review_id: "2",date: time.Now().AddDate(0, 0, 7*1)})
    listOfReviews = append(listOfReviews, reviews_data{review_id: "1",date: time.Now().AddDate(0, 0, 7*-1)})

    sort.Slice(listOfReviews, func(i, j int) bool { return listOfReviews[i].date.Before(listOfReviews[j].date) })
}

答案4

得分: 0

// 按日期排序

type Location struct {
  Lat     float64   `json:"lat"`
  Lng     float64   `json:"lng"`
  Thetime time.Time `json:"thetime"`
}

func sorttime(dat []Location) {
  for i := 0; i < len(dat); i++ {
    for j := i + 1; j < len(dat); j++ {
      if dat[i].Thetime.Unix() < dat[j].Thetime.Unix() {
        dat[i], dat[j] = dat[j], dat[i]
      }
    }
  }
}

<details>
<summary>英文:</summary>

&gt; sorting dates

type Location struct {
Lat float64 json:&quot;lat&quot;
Lng float64 json:&quot;lng&quot;
Thetime time.Time json:&quot;thetime&quot;
}
func sorttime(dat []Location) {
for i := 0; i < len(dat); i++ {
for j := i + 1; j < len(dat); j++ {
if dat[i].Thetime.Unix() < dat[j].Thetime.Unix() {
dat[i], dat[j] = dat[j], dat[i]
}
}
}
}


</details>



huangapple
  • 本文由 发表于 2014年4月17日 06:08:04
  • 转载请务必保留本文链接:https://go.coder-hub.com/23121026.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定