简体   繁体   中英

setting a format for a date in ms access

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;

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

为什么不使用SQL提取日期部分?

SELECT DatePart('d', [date]) as theDay FROM Attendance

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM