我在项目中使用flutter。
我从服务器获取对象数组。每个对象包含几个属性,其中之一是日期属性。
这是我从服务器获取的数组(json 格式):
{
"drainageid": "",
"datacount": 98359,
"resultcount": 98359,
"page": "",
"rows": [
{
"id": "DR/C1/IC/H/-/GPG/PU/-/RCP/01",
"dateoflastinsp": null,
"dateofinsp": "2001-10-10T00:00:00",
"inspby": "SAW/ZAG"
},
{
"id": "DR/C1/IC/H/-/GPG/PU/-/RCP/01",
"dateoflastinsp": "2001-10-10T00:00:00",
"dateofinsp": "2002-09-24T00:00:00",
"inspby": "SAW+NBN"
},
{
"id": "DR/C1/IC/H/-/GPG/PU/-/RCP/01",
"dateoflastinsp": "2002-09-24T00:00:00",
"dateofinsp": "2003-09-18T00:00:00",
"inspby": "SAW/NBN"
},
{
"id": "DR/C1/IC/H/-/GPG/PU/-/RCP/01",
"dateoflastinsp": "2003-09-18T00:00:00",
"dateofinsp": "2004-09-08T00:00:00",
"inspby": "SAW/NBN"
},
{
"id": "DR/C1/IC/H/-/GPG/PU/-/RCP/01",
"dateoflastinsp": "2004-09-08T00:00:00",
"dateofinsp": "2005-05-05T00:00:00",
"inspby": "MZB/ASMG"
},
{
"id": "DR/C1/IC/H/-/GPG/PU/-/RCP/01",
"dateoflastinsp": "2005-05-05T00:00:00",
"dateofinsp": "2006-05-04T00:00:00",
"inspby": "MZB/ASZ"
},
{
"id": "DR/C1/IC/H/-/GPG/PU/-/RCP/01",
"dateoflastinsp": "2006-05-04T00:00:00",
"dateofinsp": "2007-05-09T00:00:00",
"inspby": "Ahmad/Haizul"
},
{
"id": "DR/C1/IC/H/-/GPG/PU/-/RCP/01",
"dateoflastinsp": "2007-05-09T00:00:00",
"dateofinsp": "2008-05-07T00:00:00",
"inspby": "Harzazi/Zulkornain"
},
}
我需要从
dateoflastinsp
列表中的数组中获取最新日期 rows
。
如何从flutter中的对象数组中获取最新日期?
您可以使用
List.sort
并比较日期。
String jsonData = '''
{
"drainageid": "",
"datacount": 98359,
"resultcount": 98359,
"page": "",
"rows": [
{
"id": "DR/C1/IC/H/-/GPG/PU/-/RCP/01",
"dateoflastinsp": null,
"dateofinsp": "2001-10-10T00:00:00",
"inspby": "SAW/ZAG"
}...
''';
// Parse the JSON data
Map<String, dynamic> data = jsonDecode(jsonData);
// Sort the rows by dateofinsp in ascending order
List<Map<String, dynamic>> rows = List<Map<String, dynamic>>.from(data['rows']);
rows.sort((a, b) => DateTime.parse(a['dateofinsp']).compareTo(DateTime.parse(b['dateofinsp'])));
// Print the sorted rows
for (Map<String, dynamic> row in rows) {
print(row);
}
输出
{id: DR/C1/IC/H/-/GPG/PU/-/RCP/01, dateoflastinsp: null, dateofinsp: 2001-10-10T00:00:00, inspby: SAW/ZAG}
{id: DR/C1/IC/H/-/GPG/PU/-/RCP/01, dateoflastinsp: 2001-10-10T00:00:00, dateofinsp: 2002-09-24T00:00:00, inspby: SAW+NBN}
{id: DR/C1/IC/H/-/GPG/PU/-/RCP/01, dateoflastinsp: 2002-09-24T00:00:00, dateofinsp: 2003-09-18T00:00:00, inspby: SAW/NBN}
{id: DR/C1/IC/H/-/GPG/PU/-/RCP/01, dateoflastinsp: 2003-09-18T00:00:00, dateofinsp: 2004-09-08T00:00:00, inspby: SAW/NBN}
{id: DR/C1/IC/H/-/GPG/PU/-/RCP/01, dateoflastinsp: 2004-09-08T00:00:00, dateofinsp: 2005-05-05T00:00:00, inspby: MZB/ASMG}
{id: DR/C1/IC/H/-/GPG/PU/-/RCP/01, dateoflastinsp: 2005-05-05T00:00:00, dateofinsp: 2006-05-04T00:00:00, inspby: MZB/ASZ}
{id: DR/C1/IC/H/-/GPG/PU/-/RCP/01, dateoflastinsp: 2006-05-04T00:00:00, dateofinsp: 2007-05-09T00:00:00, inspby: Ahmad/Haizul}
{id: DR/C1/IC/H/-/GPG/PU/-/RCP/01, dateoflastinsp: 2007-05-09T00:00:00, dateofinsp: 2008-05-07T00:00:00, inspby: Harzazi/Zulkornain}