登录
首页 >  Golang >  Go问答

按创建日期排序列表 golang

来源:stackoverflow

时间:2024-04-21 08:18:39 352浏览 收藏

今日不肯埋头,明日何以抬头!每日一句努力自己的话哈哈~哈喽,今天我将给大家带来一篇《按创建日期排序列表 golang》,主要内容是讲解等等,感兴趣的朋友可以收藏或者有更好的建议在评论提出,我都会认真看的!大家一起进步,一起学习!

问题内容

我有一个返回 inspections 模型实例的函数,我想通过 createddate 对其进行 sort 但在编译后我得到了

不能在返回参数中使用 inspections[i].createddate (字符串类型)作为 bool 类型

inspection.go

type inspection struct {
    id          int64               `db:"id,omitempty" json:"id,omitempty"`
    createddate string              `db:"created,omitempty" json:"created_date,omitempty"`
    records     []*inspectionrecord `db:"-" json:"records,omitempty"`
    inspectionfields
}

list.go

import (
    "sort"
)

func (s *Manager) list(fields *inspection.ItemIdField) (*inspection.InspectionHistoryResponse, error) {
    return s.listItemInspectionHistory(fields.ItemId)
}

func (s *Manager) listItemInspectionHistory(itemId string) (*inspection.InspectionHistoryResponse, error) {
    g := config.Client.Inspections()

    var inspections []*models.Inspection

    inspections, err := g.FindInspections(itemId)

    if err != nil {
        s.Log.Debugf("Can't find inspections of item with id %s", itemId)
        return nil, err
    }
    s.Log.Debugf("Found %d inspections for item with id %s", len(inspections), itemId)

    for _, inspection := range inspections {
        inspection.Records, err = g.FindRecords(inspection.Id)
        if err != nil {
            s.Log.Debugf("Can't find records for inspection with id %d", inspection.Id)
            return nil, err
        }
        s.Log.Debugf("Found %d records for inspection with id %d", len(inspection.Records), inspection.Id)
    }

    model := new(models.InspectionHistory)
    model.Inspections = inspections
    // sort by CreatedDate
    sort.Slice(inspections, func(i, j int) bool { return inspections[i].CreatedDate })

    return transform.InspectionHistoryModelToProtobufResponse(model)
}

错误很明显,但我对如何解决它有点困惑,有人可以向我解释如何解决这个问题吗?谢谢。


解决方案


您必须解析日期字符串并将它们作为 time.Time 个实例进行比较

假设您有一个有效的日期,并且他们的号码是 RFC3339,您可以执行以下操作

sort.Slice(inspections, func(i, j int) bool {
        t1, _ := time.Parse(time.RFC3339, inspections[i].CreatedDate)
        t2, _ := time.Parse(time.RFC3339, inspections[j].CreatedDate)
        return t1.After(t2)
    })

终于介绍完啦!小伙伴们,这篇关于《按创建日期排序列表 golang》的介绍应该让你收获多多了吧!欢迎大家收藏或分享给更多需要学习的朋友吧~golang学习网公众号也会发布Golang相关知识,快来关注吧!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>