Sunday, January 22, 2017



Sort dates from a array of String

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Arrays;
public class SortDatesFromStringArray{

public static void main(String args[])
{

String[]dates={"01/28/2019","01/30/2017","01/28/2017","01/27/2017","01/28/2018"};
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy");

 try {
                
Date[] arrayOfDates = new Date[dates.length];
for (int index = 0; index < dates.length; index++) {
    arrayOfDates[index] = sdf.parse(dates[index]);
}


Arrays.sort(arrayOfDates);
for (int index = 0; index < dates.length; index++) {
    dates[index] = sdf.format(arrayOfDates[index]);
System.out.println(dates[index]);
}
  
                } catch (ParseException ex) {
                    ex.printStackTrace();
                }
}

}



 

No comments:

Post a Comment