Pergunta

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;

Foi útil?

Solução

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

Outras dicas

Why not use SQL to extract the day part?

SELECT DatePart('d', [date]) as theDay FROM Attendance
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top