0

I'm trying to format a date formatted result from a database into date only. ("dd"). The query results are formatted like this, 2014-05-17 00:00:00 I want to extract only "17", How can I achieved this? This is my code.

String query = "SELECT DISTINCT date FROM Attendance;";
            Object[][] queryResult = connectToDB(headerQuery);

            for(int x = 0; x < queryResult.length; x++){
                for(int y=0; y < queryResult[x].length; y++){
                    Object temp = queryResult[x][y];
                    SimpleDateFormat format = new SimpleDateFormat("dd");
                    System.out.print(format.format(temp));
                    System.out.println(temp+ "<-----");
                }
                System.out.println("---");
            }

this is my error

Exception in thread "AWT-EventQueue-0" java.lang.ClassCastException: java.lang.String cannot be cast to java.util.Date

UPDATE: I've changed the for-loop into this:

for(int x = 0; x < queryResult.length; x++){
                for(int y=0; y < queryResult[x].length; y++){
                    String temp = (queryResult[x][y]).toString();
                    SimpleDateFormat format = new SimpleDateFormat("dd");
                    Date date = (Date) format.parse(temp);

                    System.out.println(date+ "<-----");
                }
                System.out.println("---");
            }

but it still does not format the date;

Frakcool
  • 10,915
  • 9
  • 50
  • 89
Rocky
  • 429
  • 1
  • 9
  • 26
  • It seems that `Object temp = headerQueryResult[x][y];` is of type `String`. What is the output of `System.out.println(temp+ "<-----"); `? – Meno Hochschild May 15 '14 at 17:16

2 Answers2

0

OK so you're trying to format a String. That is, temp is a String and you can't pass that into format. You need to turn that String into a Date then pass it into format. Here's how.

But, even better, you should be returning a Date from the query instead of a String. That'll make your life much easier. Then you don't need to change any other part of the code.

Show us your connectToDB. Assuming it's using JDBC, you should get the result by calling ResultSet.getDate

Community
  • 1
  • 1
Daniel Kaplan
  • 62,768
  • 50
  • 234
  • 356
  • @user3615601 that won't change anything. You just casted the result, you need to *change* the input to `format`, not the output. – Daniel Kaplan May 15 '14 at 17:25
0

Why not use SQL to extract the day part?

SELECT DatePart('d', [date]) as theDay FROM Attendance
James
  • 20,957
  • 5
  • 26
  • 41