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

查看:1664
本文介绍了sort - 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

解决方案

先自己按行解析出来,解析成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
}

这篇关于sort - golang怎么对日期和时间进行排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆