如何在java中从org.json.jsonarray获取时间间隔数据?

vnzz0bqm  于 2021-06-29  发布在  Java
关注(0)|答案(1)|浏览(300)

我有以下数据:

[{
    "DT": "2020-12-18 09:20:00",
    "High": 1432.15,
    "Open": 1425.8
}, {
    "DT": "2020-12-18 09:25:00",
    "High": 1425,
    "Open": 1424
}, {
    "DT": "2020-12-18 09:30:00",
    "High": 1423.1,
    "Open": 1423.1
}, {
    "DT": "2020-12-18 09:35:00",
    "High": 1421.1,
    "Open": 1419.15
}, {
    "DT": "2020-12-18 09:40:00",
    "High": 1420.85,
    "Open": 1418.7
}, {
    "DT": "2020-12-18 09:45:00",
    "High": 1418.9,
    "Open": 1415.85
}, {
    "DT": "2020-12-18 09:50:00",
    "High": 1418.9,
    "Open": 1418.5
}]

但我需要这样的数据:
间隔10分钟:

[{
    "DT": "2020-12-18 09:20:00",
    "High": 1432.15,
    "Open": 1425.8
},  {
    "DT": "2020-12-18 09:30:00",
    "High": 1423.1,
    "Open": 1423.1
},  {
    "DT": "2020-12-18 09:40:00",
    "High": 1420.85,
    "Open": 1418.7
}, {
    "DT": "2020-12-18 09:50:00",
    "High": 1418.9,
    "Open": 1418.5
}]

间隔15分钟

[{
    "DT": "2020-12-18 09:20:00",
    "High": 1432.15,
    "Open": 1425.8
},{
    "DT": "2020-12-18 09:35:00",
    "High": 1421.1,
    "Open": 1419.15
}, {
    "DT": "2020-12-18 09:50:00",
    "High": 1418.9,
    "Open": 1418.5
}]
2lpgd968

2lpgd9681#

java 8及以上版本
创建下面的方法并调用 JSONArray tenMinutesArray = filterData( originalJSONArray, 10 ); ```
private static JSONArray filterData( JSONArray values, int interval ) {
JSONArray newArray = new JSONArray();
newArray.put( values.getJSONObject( 0 ) );
LocalDateTime start = parseDate( values.getJSONObject( 0 ).getString( "DT" ) );

for ( int i = 1; i < values.length(); i++ ) {
    JSONObject entry = values.getJSONObject( i );
    LocalDateTime dt = parseDate( entry.getString( "DT" ) );
    int diff = dt.minusMinutes( start.getMinute() ).getMinute();
    if ( diff % interval == 0 ) {
        newArray.put( entry );
    }
}
return newArray;

}

private static LocalDateTime parseDate( String dateTime ) {
return LocalDateTime.parse( dateTime.replaceAll( " ", "T" ) );
}

java 7及更高版本
这是用乔达时间最容易做到的。
将依赖项添加到 `<dependencies>` pom.xml中的节点:
for ( int i = 1; i < values.length(); i++ ) {
    JSONObject entry = values.getJSONObject( i );
    DateTime dt = parseDate( entry.getString( "DT" ) );
    Minutes diff = Minutes.minutesBetween( start, dt );
    if ( diff.getMinutes() % interval == 0 ) {
        newArray.put( entry );
    }
}
return newArray;

}

private static DateTime parseDate( String dateTime ) {
return DateTime.parse( ( dateTime + "Z" ).replaceAll( " 0?", "T" ) );
}

相关问题