按创建日期golang排序列表

问题描述 投票:-2回答:1

我有一个函数返回Inspections的模型实例,我想通过sort CreatedDate但是我编译后我已经有了

不能使用检查[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)
}

错误是显而易见的,但我对如何解决它有点困惑,有人可以向我解释如何解决这个问题?谢谢。

go
1个回答
3
投票

您必须解析Date字符串并将它们作为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)
    })
© www.soinside.com 2019 - 2024. All rights reserved.