Java program to sort arrays containing dates
Hi There:
I have an array of strings which will contain a date in the following order DD-MM-YYYY and what I would really like to do is SORT that array. What I am currently doing is:
Code :
Arrays.sort(actDate,0,actDate.length);
By the way, actDate is an array strings that will contain a date (but in string format) like DD-MM-YYYY in decimal (ex: 21-0-2009)
And i know I cannot sort null values, I am (at this point) assuming the array is full
What I was thinking of doing is converting (21-05-2009) into the date format and then sorting an array of dates? Would this work? here is my proposal:
Code :
private static final String VALID_DATE_REGEX = "(0[1-9]|[12][0-9]|3[01])[-](0[1-9]|1[012])[-](20\\d\\d)";
private static final Pattern DATE_PATTERN = Pattern.compile(VALID_DATE_REGEX);
Matcher mDateMatch = DATE_PATTERN.matcher( actDate );
/// here I would loop through the array of string that I have now and convert them to a date by breaking up the day, month, year like I show below
int nDay = Integer.parseInt( mDateMatch.group(1) );
int nMonth = Integer.parseInt( mDateMatch.group(2) );
int nYear = Integer.parseInt( mDateMatch.group(3) );
Date dNewDate = new Date(nYear, nMonth, nDay); // problem is that this is depreciated
Am I close...how would you do this?
Thanks!
Adam Scott
Re: Sorting an array which I hope to fill with dates
You can use SimpleDateFormat class. For example:
Code :
SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy");
Date date = sdf.parse("09-03-2009");
Date date2 = sdf.parse("09-02-2009");
Date[] d = { date, date2 };
Arrays.sort(d);
This code will sort the array.