You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

基于含时间的createdDate实现Karate日期筛选,获取最新数据

筛选createdDate最新的记录(Groovy实现)

针对给定的Groovy列表数据,要筛选出createdDate字段最新的一条记录,可利用ISO8601格式时间字符串可直接比较的特性,通过Groovy集合的内置方法快速实现:

代码实现

def responselist = [
    ["createdDate": "2023-10-27T15:17:51.000+00:00", "createdTime": "09:17:50"],
    ["createdDate": "2023-10-28T14:08:33.000+00:00", "createdTime": "08:08:32"],
    ["createdDate": "2023-10-28T14:08:39.000+00:00", "createdTime": "08:08:39"],
    ["createdDate": "2023-10-28T14:08:43.000+00:00", "createdTime": "08:08:49"]
]

// 核心逻辑:通过max方法直接按createdDate字段比较,获取最新记录
def latestRecord = responselist.max { it.createdDate }

// 输出结果
println latestRecord

输出结果

执行后会返回createdDate最新的完整记录:

[createdDate:2023-10-28T14:08:43.000+00:00, createdTime:08:08:49]

补充实现方式

如果需要通过降序排序取第一条,也可以用以下写法:

// 按createdDate降序排序,取第一个元素
def latestRecord = responselist.sort { a, b -> b.createdDate <=> a.createdDate }[0]

原理说明

createdDate采用的ISO8601时间格式(YYYY-MM-DDTHH:mm:ss.SSSZ),字符串的字典序与时间先后顺序完全一致,因此直接比较字符串就能得到正确的时间排序结果,无需额外转换为日期对象。

内容的提问来源于stack exchange,提问作者Ajay tiruwa

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.07 14:25:04