golang怎么对日期和时间进行排序?

新手上路,请多包涵

如下一个文本文件,需要以时间的先后顺序进行排序。

 20161206             2016-12-06 13:34:31 +0800 shut off
 snapshot1            2016-06-20 15:57:35 +0800 shut off
 snapshot2            2016-03-21 15:57:25 +0800 shut off
 auto_FF_61261206_180504 2014-10-06 18:05:04 +0800 running
 auto_FF_61261206_231115 2016-12-06 13:11:15 +0800 shut off
 auto_FF_61261206_235349 2016-12-06 12:53:49 +0800 running
阅读 11.1k
1 个回答

先自己按行解析出来,解析成map[string]string
要是想解析成[]map[string]string 就把下面代码改改就行

import "sort"
type MapSorter []SortItem

type SortItem struct {
    Key string      `json:"key"`
    Val interface{} `json:"val"`
}

func (ms MapSorter) Len() int {
    return len(ms)
}
func (ms MapSorter) Less(i, j int) bool {
    return ms[i].Key < ms[j].Key // 按键排序
    // return ms[i].Value <ms[j].Value //按值排序
}
func (ms MapSorter) Swap(i, j int) {
    ms[i], ms[j] = ms[j], ms[i]
}

func MapSort(m map[string]string) []map[string]string {
    ms := make(MapSorter, 0, len(m))

    for k, v := range m {
        ms = append(ms, SortItem{k, v})
    }
    sort.Sort(ms)
    result:=[]map[string]string
    for _, p := range ms {
        result=append(result,map[string]string{p.Key:p.Value})
    }
    return result
}
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题