时间排序
给出多个时间,获取离现在最近的时间,并且与当前时间相差多少毫秒。
public static void main(String[] args) throws ParseException {
Map<String, Long> map = dateDistance("2019-11-22 10:38:00","2019-09-07 20:09:39","2019-11-22 10:52:00","2019-11-22 10:42:00");
System.out.println(map.toString());
}
public static Map<String,Long> dateDistance(String ... data) throws ParseException {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Map<String,Long> map = new HashMap<>(data.length);
//循环取出可变参数中的所有数据,并存入Map中,key为当前传入的时间,value为该时间与当前时间戳的差
for (int i=0 ;i<data.length;i++){
long time = dateFormat.parse(data[i]).getTime();
//保存数据
map.put(data[i],System.currentTimeMillis() - time);
}
//根据Map的key从小到大排序
List<Map.Entry<String,Long>> list = new ArrayList(map.entrySet());
Collections.sort(list, (o1, o2) -> (int) (Math.abs(o1.getValue()) - Math.abs(o2.getValue())));
return map;
}