Link to home
Start Free TrialLog in
Avatar of rcmb
rcmb

asked on

Help with an array

I have an array that loops through my resultset and displays information. Here is my code:

while( rs.next()){
               
                 out.println("<tr>");
               
                for (int i = 1;  i <=colCount; ++i)
                    out.println("<td>" + rs.getString(i) + "</td>");
               
                 out.println("</tr>");
                         
                }

Now the problem is sometimes I display a date vice just text (or string). How can I modify the above so if a date is found it will display the date as mm/dd/yyyy but not affect how the text is displayed?

RCMB
Avatar of Mick Barry
Mick Barry
Flag of Australia image

               SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy");
                for (int i = 1;  i <=colCount; ++i)
                {
                    Object value = rs.getObject(i);
                    if (value instanceof java.sql.Date)
                    {
                       out.println("<td>" + sdf.format((java.sql.Date)value) + "</td>");
                    }
                    else
                    {
                       out.println("<td>" + value + "</td>");
                    }
Avatar of CI-Ia0s
CI-Ia0s

>>How can I modify the above so if a date is found it will display the date as mm/dd/yyyy but not affect how the text is displayed?

How is the date displayed now?
Avatar of rcmb

ASKER

It displays as yyyy-mm-dd 00:00:00.0

RCMB
Do what objects said. ;)

Or, if you want to do it the hard way, you could use any conditional that tells you it's a date (for instance, if you know only dates will have "-" in them, then if (rs.getString(i).indexOf("-") > -1) ).

Then you could manually rearrange the date, i.e.:
String finalDate = rs.getString(i).substring(5,8) + rs.getString(i).substring(8,10) + "-" + rs.getString(i).substring(0,4);
out.println("<td>" + finalDate + "</td>");

Like, I said though, it's a lot longer. ;)
Well, I said "harder", but it's "longer" too. :P
compare ur string with the date format of
yyyy-mm-dd 00:00:00.0

 
ASKER CERTIFIED SOLUTION
Avatar of CEHJ
CEHJ
Flag of United Kingdom of Great Britain and Northern Ireland image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
ooohhh, CEHJ, please never use an exception handler when simple if condtions will do.

Why hasn't anyone suggested using the ResultSetMetaData to see what kind of data is in each column as it is retrieved?

Something like:

            ResultSetMetaData metaData = resultSet.getMetaData();
           
            int columns = metaData.getColumnCount();
           
            while( resultSet.next() ) {

                String row[] = new String[ columns ];

                for (int i = 1; i <= columns; i++) {

                    switch( metaData.getColumnType(i) ) {
                   
                        case java.sql.Types.CLOB:
                            Clob clob =  resultSet.getClob(i); // BEWARE ORACLE ONLY CODE
                            // FIXME! max we have is 4000 bytes. so it is assumed ok.
                            row[ i - 1 ] = clob.getSubString( 1/* from the begining */, (int) clob.length()/* till the end */);
                            break;

                        case java.sql.Types.DATE:
                             // do the dateformatting here to get the appropropriate string representation

                        default:
                            row[ i - 1 ] = resultSet.getString(i);
                            break;

                    }    

                }

Avatar of rcmb

ASKER

To all:

I have implemented objects suggestion and it is still not working. My SQL 2K database field is a date value. I receive no errors and all returns as expected except for the date display.

Here is my code:

while( rs.next()){
               
out.println("<tr>");
               
for (int i = 1;  i <=colCount; ++i) {
                        
Object value = removeNull(rs.getObject(i)); //I use removeNull to not display a Null value
if (value instanceof Date) {
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy");
out.println("<td>" + sdf.format(value) + "</td>");
} else {
out.println("<td>" + value + "</td>");
}
}
out.println("</tr>");
}
                        
} catch (Exception e){
           
throw new ServletException(e.getMessage());

Here is my display results:

Last Name First Name PRD EAOS
MERRILL ERIC 1955-01-01 00:00:00.0 1955-01-01 00:00:00.0
SHREFFLER BRANDON 2004-05-01 00:00:00.0 2004-10-09 00:00:00.0
MEADOR TYLER 2005-04-01 00:00:00.0 1999-01-01 00:00:00.0
BAUMAN WILLIAM 2005-05-01 00:00:00.0 2005-03-14 00:00:00.0
DEAN DAVID 2005-06-15 00:00:00.0 2005-06-15 00:00:00.0
DIAZ ENRIQUE 2006-02-01 00:00:00.0 2004-10-19 00:00:00.0
WINDHAM KEVIN 2006-04-01 00:00:00.0 2009-04-01 00:00:00.0
LEWIS ROBERT 2006-06-01 00:00:00.0 2006-10-30 00:00:00.0
WOODS ELDRICK 2007-09-01 00:00:00.0  
Avatar of rcmb

ASKER

sbockleman --

I am somewhat new to this arena so how can I write your code to not include the Oracle data?

RCMB
Have you tried my simpler suggestion (albeit, longer) suggestion? Checking for either a dash ("-") or a colon (":") would indicate a date, and then you can just rearrange it piece by piece via substring... Unless there's more to this than meets the eye?
>>I have implemented objects suggestion and it is still not working.

This suggests that your dates are *not* stored as Date. My suggestion should work

>>ooohhh, CEHJ, please never use an exception handler when simple if condtions will do.

Perhaps you could kindly suggest how one can do if(parseableInThatFormat) without using regular expressions then?
I guess my first response was a bit reckless...sorry...I was in a hurry and didn't make everything I was trying to suggest very clear, especially my recommendation that the try/catch construct not be used in situations such as this where the performance would almost certainly be negatively impacted (since, all but one or two iterations of the loop would NOT throw an exception).

What I would suggest (aside from the high-level eyebrow raising that business logic and presentation semantics are being comingled), goes something like this:

ResultSet rs = <get your results here>;

ResultSetMetaData metaData = rs.getMetaData();
           
int columns = metaData.getColumnCount();

String s  = "";
           
while( rs.next() ) {

    for (int i = 1; i <= columns; i++) {

        switch( metaData.getColumnType(i) ) {

             case java.sql.Types.DATE:
                   Date date = rs.getDate( i );
                   if( !rs.wasNull() ) {
                       SimplateDateFormat df = new SimpleDateFormat( "MM/dd/yyyy" );
                       s = date.toString();
                       try {
                           s = df.format( date );
                       } catch( Exception e ) {
                           // log this (for instance with commons-logging or log4j or at the very least System.out);
                       }
                   }
                   break;

             case java.sql.Types.TIMESTAMP:
                   Timestamp date = rs.getTimestamp( i );
                   if( !rs.wasNull() ) {
                       SimplateDateFormat df = new SimpleDateFormat( "MM/dd/yyyy" );
                       s  = date.toString();
                       try {
                           s  = df.format( date );
                       } catch( Exception e ) {
                           // log this (for instance with commons-logging or log4j or at the very least System.out);
                       }
                   }
                   break;

                   default:
                        s = rs.getString();
                        if( rs.wasNull() || "null".equals( s ) ) {
                             s = "";
                        }
                        break;
        }

    }

}


Obviously, you'll want to do something with the values (I guess in your case, write them to the response).

Why I reacted so stringly to the suggestion from CEHJ is that:

1.  exception handlers without any code statements are automatically suspiscious (Beck and Fowler call this a "code smell")

2.  catching an exception is definitely more "expensive" than an if condition, when possible.

3.  we can avoid trying to parse every column, since we can check whether its data type is even a date or timestamp.

I hope the information her is helpful.

You might also try editing the SQL Query itself to do the conversion from the table column's date to a string.  I cannot recall the SQLServer/T-SQL way off-hand  -- probably something like CStr( date_column ) --  in Oracle you would use TO_CHAR( date_column, 'MM/dd/yyyy' ) in the select clause.

Good luck.

> if (value instanceof Date) {

that should be

if (value instanceof java.sql.Date) {
Avatar of rcmb

ASKER

Well I spent most of the night trying every example provided.

Objects -- I did try it with java.sql.Date and it does not work -- The reason I did not have it on my code was because I imported java.sql.*

sbockelman -- everytime I ran your code I received errors. Not sure where it was failing or what I was doing wrong.

CEHJ -- Your example works fine. No tweeking needed and it worked just like I desired.

Thanks to all for your time.
8-)