ron
ron

Reputation: 5289

java.sql.timestamp versus date

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.

Upvotes: 1

Views: 2313

Answers (1)

stacker
stacker

Reputation: 68992

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.

Upvotes: 1

Related Questions