1

I am using Derby database with Java and Eclipse. I have a table which has a TIMESTAMP field and I use a model to populate a JTable from it. I am finding timestamp and data and java.sql and java.utils very confusing. The following line of code errors with cannot cast date to timestamp. mod is the model interfacing Derby table and JTable.

int rowcount = mod.getRowCount();
java.sql.Timestamp ts = (java.sql.Timestamp) mod.getValueAt(rowcount-1,1);

My objective is to get the date of the most recent record and subtract 30 days then run an sql query on the same database to find all the records more recent than that date. How do I recover the first timestamp, subtract the 30 days, then construct a query with the result of the subtraction as the condition in a WHERE clause. Sounds simple but I am having such difficulty that I feel I must be missing some fundamental principal. I thought conversion to long and back again might be the route but came up against the same cast problem.

1
  • Can't you use Derby built-in date functions to accomplish everything in one sql-request? Commented Jan 16, 2012 at 9:13

1 Answer 1

1

Timestamp is declared as

public class Timestamp extends java.util.Date { ... }

Therefore you can't cast date to timstamp, you could create a timestamp from a date.

Timstamp ts = new Timestamp( date.getTime() );

To subtract 30 days this sequence might be helpful:

Calendar cal = new GregorianCalendar();
cal.setTime( date.getTime() );
cal.add( Calendar.DAY_OF_MONTH, -30 );
Date d30 = cal.getTime();

Anyway I would try to perform this using only SQL.

Sign up to request clarification or add additional context in comments.

4 Comments

java.util.Date ts = (java.util.Date)mod.getValueAt(rowCount-1,1);
myResult = statement .executeQuery("SELECT * FROM MYENERGYAPP.energytable9 WHERE MYDATETIME > "+ "{fn TIMESTAMPADD(SQL_TSI_MONTH, -1,timestamp('"+ts+"'))}");
The above 2 comments were added before I intended - they are the solution I finally came up with.
@ron you can always submit your own answer to your question, rather than post a series of comments which are hard to format / read.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.