Solved

Help with an array

Posted on 2004-09-17
16
240 Views
Last Modified: 2010-03-31
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
0
Comment
Question by:rcmb
  • 4
  • 4
  • 3
  • +3
16 Comments
 
LVL 92

Expert Comment

by:objects
ID: 12089641
               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>");
                    }
0
 
LVL 3

Expert Comment

by:CI-Ia0s
ID: 12089644
>>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?
0
 
LVL 12

Author Comment

by:rcmb
ID: 12089663
It displays as yyyy-mm-dd 00:00:00.0

RCMB
0
 
LVL 3

Expert Comment

by:CI-Ia0s
ID: 12089695
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. ;)
0
 
LVL 3

Expert Comment

by:CI-Ia0s
ID: 12089697
Well, I said "harder", but it's "longer" too. :P
0
 
LVL 2

Expert Comment

by:jprgn
ID: 12090780
compare ur string with the date format of
yyyy-mm-dd 00:00:00.0

 
0
 
LVL 86

Accepted Solution

by:
CEHJ earned 500 total points
ID: 12090987
>>sometimes I display a date vice just text (or string).

Depends on how the dates are stored, if they're stored as Date, then use objects' code. If they're stored as Strings, you can use this:

SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.S");
SimpleDateFormat sdf2 = new SimpleDateFormat("MM/dd/yyyy");
sdf1.setLenient(false);
while (rs.next()) {
      for (int i = 1;  i <=colCount; ++i) {
            String value = rs.getString(i);
            try {
                  Date d = sdf1.parse(value);
                  value = sdf2.format(d);
            }
            catch(Exception e) {
                  /* ignore - it's not a Date */
            }
            out.println("<td>" + value + "</td>");
      }
}      
0
 
LVL 3

Expert Comment

by:sbockelman
ID: 12093027
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;

                    }    

                }

0
Do You Know the 4 Main Threat Actor Types?

Do you know the main threat actor types? Most attackers fall into one of four categories, each with their own favored tactics, techniques, and procedures.

 
LVL 12

Author Comment

by:rcmb
ID: 12093850
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  
0
 
LVL 12

Author Comment

by:rcmb
ID: 12093854
sbockleman --

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

RCMB
0
 
LVL 3

Expert Comment

by:CI-Ia0s
ID: 12094234
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?
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 12094761
>>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?
0
 
LVL 3

Expert Comment

by:sbockelman
ID: 12095717
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.

0
 
LVL 92

Expert Comment

by:objects
ID: 12097994
> if (value instanceof Date) {

that should be

if (value instanceof java.sql.Date) {
0
 
LVL 12

Author Comment

by:rcmb
ID: 12101190
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.
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 12101215
8-)
0

Featured Post

Top 6 Sources for Identifying Threat Actor TTPs

Understanding your enemy is essential. These six sources will help you identify the most popular threat actor tactics, techniques, and procedures (TTPs).

Join & Write a Comment

Suggested Solutions

INTRODUCTION Working with files is a moderately common task in Java.  For most projects hard coding the file names, using parameters in configuration files, or using command-line arguments is sufficient.   However, when your application has vi…
Introduction This article is the second of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article covers the basic installation and configuration of the test automation tools used by…
This tutorial covers a practical example of lazy loading technique and early loading technique in a Singleton Design Pattern.
This video teaches viewers about errors in exception handling.

757 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

17 Experts available now in Live!

Get 1:1 Help Now