我想在Java上问一些问题。我有从JSON数据解析的时间(字符串)列表。我需要找到哪个时间更接近系统时间。这样,现在时间是16:40。我的时间清单包含 “ 16:32”,“ 16:38”,“ 16:44”,“ 16:50”等。对于16:40,16:38比16:44更近,我需要找到它。我试图获取当前索引和下一个索引,解析它们并初始化新的日历等等。但是我不知道下一步该怎么做。
任何解决此问题的方法?
String returnTime = current.getDonus();
if (i < list.size() + 1) {
TimeList nextOne=list.get(i+1);
String nextReturnTime = nextOne.getDonus();
String[] parsedNextReturn = nextReturnTime.split(":");
String[] parsedReturn = returnTime.split(":");
Date date = new Date();
Calendar calNextReturn= Calendar.getInstance();
calNextReturn.setTime(date);
calNextReturn.set(Calendar.HOUR_OF_DAY, Integer.parseInt(parsedNextReturn[0]));
calNextReturn.set(Calendar.MINUTE, Integer.parseInt(parsedNextReturn[1]));
calNextReturn.set(Calendar.SECOND, 0);
calNextReturn.set(Calendar.MILLISECOND, 0);
Calendar calCurrentReturn= Calendar.getInstance();
calCurrentReturn.setTime(date);
calCurrentReturn.set(Calendar.HOUR_OF_DAY, Integer.parseInt(parsedReturn[0]));
calCurrentReturn.set(Calendar.MINUTE, Integer.parseInt(parsedReturn[1]));
calCurrentReturn.set(Calendar.SECOND, 0);
calCurrentReturn.set(Calendar.MILLISECOND, 0);
Calendar calSystem = Calendar.getInstance();
calSystem.setTime(date);
calSystem.set(Calendar.SECOND, 0);
calSystem.set(Calendar.MILLISECOND, 0);
}
答案 0 :(得分:1)
尝试一下:
long smallestABS = Long.MAX_VALUE;
long systemTime = System.currentTimeMillis();
long timeClosest;
for (long time : timeList) {
long abs = Math.abs(systemTime - time);
if(smallestABS > abs){
smallestABS = abs;
timeClosest = time;
}
}