Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations bkrike on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Sorting string based on date/time

Status
Not open for further replies.

adrianjohnson

Programmer
May 16, 2002
145
GB
Hi everyone,

I've written some Java which reads a text file, and then puts each line from the text file into an array. I then loop through each element, and seperate bits (such as data/time, details etc) and put them into seperate arrays for processing later on.

An example is:
22/07/2004-10:00-Log entry

However, as the entries in the text file aren't ordered, I want to display the entries in a list box, but in date/time order. I've looked at sorting arrays, but wondered if anyone had any code to hand that helps.

Let me know if you need more info.

Thanks,

Adrian Johnson
 
I think this example you will find is much simpler, and more flexible, as there is no messing with StringTokenizers or whatever, and you can format your dates much more easily :

Code:
import java.util.*;
import java.text.*;

public class Test {
 	public static void main(String args[]) throws Exception {
		Date[] arr = new Date[3];
		int i = 0;
		SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy-HH:mm-");
		String inString = "24/07/2004-10:00-Log entry";
		java.util.Date master = sdf.parse(inString, new ParsePosition(0));
		arr[i++] = master;
		inString = "22/07/2004-10:30-Log entry";
		master = sdf.parse(inString, new ParsePosition(0));
		arr[i++] = master;
		inString = "23/07/2004-10:15-Log entry";
		master = sdf.parse(inString, new ParsePosition(0));
		arr[i++] = master;

		Arrays.sort(arr);

		sdf = new SimpleDateFormat("E dd MMM yy");
		for (i = 0; i < arr.length; i++) {
			System.out.print(arr[i]);
			String formattedDate = sdf.format(arr[i]);
			System.out.println("\t\t - \t" +formattedDate);
		}

	}

}


--------------------------------------------------
Free Database Connection Pooling Software
 
Can you change the format of the date? Because ISO-8601 format naturally sorts:
yyyy-mm-ddThh:mm:ss

Chip H.


____________________________________________________________________
If you want to get the best response to a question, please read FAQ222-2244 first
 
Thanks sedj.

I put some of the code in a loop, as I'm not sure how many entries there'd be. However, I get the following errors or the Arrays.sort(arr) line:

java.lang.NullPointerException
at java.util.Arrays.mergeSort(Unknown Source)
at java.util.Arrays.sort(Unknown Source)

What have I done wrong?
 
Use an ArrayList to add the String/Date objects, then convert to a Date array like so :

Code:
import java.util.*;
import java.text.*;

public class Test {
 	public static void main(String args[]) throws Exception {
		ArrayList al = new ArrayList();
		int i = 0;
		SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy-HH:mm-");
		String inString = "24/07/2004-10:00-Log entry";
		java.util.Date master = sdf.parse(inString, new ParsePosition(0));
		al.add(master);
		inString = "22/07/2004-10:30-Log entry";
		master = sdf.parse(inString, new ParsePosition(0));
		al.add(master);
		inString = "23/07/2004-10:15-Log entry";
		master = sdf.parse(inString, new ParsePosition(0));
		al.add(master);

		Object[] arr = al.toArray();
		Arrays.sort(arr);

		sdf = new SimpleDateFormat("E dd MMM yy");
		for (i = 0; i < arr.length; i++) {
			Date d = (Date)arr[i];
			System.out.print(d);
			String formattedDate = sdf.format(d);
			System.out.println("\t\t - \t" +formattedDate);
		}

	}

}

--------------------------------------------------
Free Database Connection Pooling Software
 
It doesn't like the first line in the for loop :

java.lang.ClassCastException: java.lang.String
at com.assystance.breaktime.ScreenDisplay.<init>(ScreenDisplay.java:139)

Line 139 being:

Date d = (Date)arr;
 
Still doesn't like the sort.

Some of the code is below. Let me know if you need it all, but it's a little long.

Code:
// Array to hold the lines from the file.
        Object[] array = al.toArray();
        int arraycount = array.length;
        
        // Strings to hold elements of the appointment.
        String[] remdate = new String[arraycount];
        String[] remtime = new String[arraycount];
        String[] apptdate = new String[arraycount];
        String[] appttime = new String[arraycount];
        String[] apptdetails = new String[arraycount];
        
        String[] appointment = new String[arraycount];
        
        // String variable to hold each array line, it's length, and
        // the start point of the reminder date/time temporarily.
        String tmparray;
        int tmparraylen;
        int remdatest;
        
        // String to hold the reminder date and time, to compare with current
        // date and time.
        String remdatetime;
        
        ArrayList ald = new ArrayList();
        int i = 0;
        SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy-HH:mm-");
        
        String inString;
        
        // Print the contents of the file to the system window.
        for (int count = 0; count < array.length; count++)
        {
            //System.out.println(array[count]);
            tmparray = array[count].toString();
            tmparraylen = tmparray.length();
            remdatest = tmparraylen - 16;
            
            // Get the appointment date and time.
            apptdate[count] = tmparray.substring(0, 10);
            appttime[count] = tmparray.substring(11, 16);
            
            // Get the reminder date and time.
            remdate[count] = tmparray.substring(remdatest, remdatest+10);
            remtime[count] = tmparray.substring(remdatest+11, tmparraylen);
            
            // Get the appointment details.
            apptdetails[count] = tmparray.substring(17, remdatest-1);
            
            // Set the string to hold the appointment details.
            appointment[count] = apptdate[count] + "-" + appttime[count] + "\n" + apptdetails[count];
            
            inString = appointment[count];
            java.util.Date master = sdf.parse(inString, new ParsePosition(0));
            ald.add(master);
            
            // Set the string containing the reminder date and time.
            remdatetime = remdate[count] + "-" + remtime[count];
        }
        
        Object[] arr = ald.toArray();
        Arrays.sort(arr);
        
        sdf = new SimpleDateFormat("E dd MMM yy");
        for (i = 0; i < arr.length; i++)
        {
            Date d = (Date)arr[i];
            System.out.print(d);
            String formattedDate = sdf.format(d);
            System.out.println("\t\t - \t" +formattedDate);
        }
 
Adrian, I'm not really sure what you are doing there, but the example I assure you works.

Here is a contained test to prove it ...

save this test data as "test.txt"
Code:
22/07/2004-10:00-Log entry
02/07/2004-10:00-Log entry
15/05/2004-10:00-Log entry
22/07/2004-10:00-Log entry
10/06/2004-10:00-Log entry
22/04/2004-10:00-Log entry
21/07/2004-10:00-Log entry
22/07/2004-10:00-Log entry
30/07/2004-10:00-Log entry

And here is the code to run - don't alter it, just save it and run it (save the test.txt in the same location as the class file).

Code:
import java.io.*;
import java.util.*;
import java.text.*;

public class Test {
 	public static void main(String args[]) throws Exception {

		ArrayList al = new ArrayList();
		java.util.Date master = null;
		SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy-HH:mm-");
		BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream("test.txt")));
		String line = "";
		while ((line = br.readLine()) != null) {
			master = sdf.parse(line, new ParsePosition(0));
			al.add(master);
		}

		Object[] arr = al.toArray();
		Arrays.sort(arr);

		sdf = new SimpleDateFormat("E dd MMM yy");
		for (int i = 0; i < arr.length; i++) {
			Date d = (Date)arr[i];
			System.out.print(d);
			String formattedDate = sdf.format(d);
			System.out.println("\t\t - \t" +formattedDate);
		}

	}

}

--------------------------------------------------
Free Database Connection Pooling Software
 
Ok, deleted my code and tried yours. However, I already have a function main, so called it something else. Because there's the throw exception bit at the end, how do I call the method?

I would normally do Test test = new Test();

but that isn't working (and my Java books aren't helping).

Thanks for your help,

Adrian Johnson
 
As I said before ...

Just save the code as Test.java, do NOT alter anything, just save it, compile it, and run it.

It will successfuly execute your problem as specified by your original post. You can use it as a basis/example to fix your own program. The only exception it will throw is IOException if the file to read is not found.

Just try to learn from examples ... there are several concepts in the given code which will address your particular problem if you apply yourself.

--------------------------------------------------
Free Database Connection Pooling Software
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top