java计算几个日期中距离现在最近的日期
public static void main(String[] args) throws Exception { String a="2019-07-26"; String b="2019-07-27"; String c="2019-07-31"; String d="2019-07-24"; String e="2019-07-01"; String f="2019-08-01"; String[] arr = new String[]{b,a,c,d,e, f}; System.out.println(getNearestDate(arr)); } private static String getNearestDate(String[] arr){ SimpleDateFormat smf = new SimpleDateFormat("yyyy-MM-dd"); long[] brr =new long[arr.length]; Map<Long,String> map = new HashMap<Long,String>(); int idx=0; for(String str : arr){ Date da = null; try { da = smf.parse(str); } catch (ParseException e) { e.printStackTrace(); } Calendar ca = Calendar.getInstance(); ca.setTime(da); long dtLong = ca.getTimeInMillis(); brr[idx]=dtLong; idx++; System.out.println(str+"--"+dtLong); map.put(dtLong, str); } Calendar ca = Calendar.getInstance(); try { ca.setTime(smf.parse( smf.format(ca.getTime() ))); } catch (ParseException e) { // TODO Auto-generated catch block e.printStackTrace(); } long dtLong = ca.getTimeInMillis(); System.out.println("now-"+dtLong); long des=0; idx=0; // 最近日期 String minDate = null; for(Long lon : brr){ long ndes = Math.abs(dtLong - lon); if(idx==0){ des = ndes; minDate=map.get(lon); } if(ndes<des){ des = ndes; minDate=map.get(lon); } idx++; } return minDate; }
取最近的日期且大于等于今天
private static String getNearestGtDate(String[] arr){ SimpleDateFormat smf = new SimpleDateFormat("yyyy-MM-dd"); long[] brr =new long[arr.length]; Map<Long,String> map = new HashMap<Long,String>(); int idx=0; for(String str : arr){ Date da = null; try { da = smf.parse(str); } catch (ParseException e) { e.printStackTrace(); } Calendar ca = Calendar.getInstance(); ca.setTime(da); long dtLong = ca.getTimeInMillis(); brr[idx]=dtLong; idx++; map.put(dtLong, str); } Calendar ca = Calendar.getInstance(); try { ca.setTime(smf.parse( smf.format(ca.getTime() ))); } catch (ParseException e) { // TODO Auto-generated catch block e.printStackTrace(); } long dtLong = ca.getTimeInMillis(); long des=0; idx=0; // 最近日期 String minDate = null; for(Long lon : brr){ if(lon>=dtLong){ long ndes = lon-dtLong ; if(idx==0){ des = ndes; minDate=map.get(lon); } if(ndes<des){ System.out.println(des); des = ndes; minDate=map.get(lon); } idx++; } } return minDate; }