简体   繁体   English

java.sql.timestamp与日期

[英]java.sql.timestamp versus date

I am using Derby database with Java and Eclipse. 我在Java和Eclipse中使用Derby数据库。 I have a table which has a TIMESTAMP field and I use a model to populate a JTable from it. 我有一个包含TIMESTAMP字段的表,并使用一个模型从中填充JTable。 I am finding timestamp and data and java.sql and java.utils very confusing. 我发现时间戳和数据以及java.sql和java.utils非常混乱。 The following line of code errors with cannot cast date to timestamp . 以下代码错误行cannot cast date to timestamp mod is the model interfacing Derby table and JTable. mod是连接Derby表和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. 我的目标是获取最新记录的日期并减去30天,然后在同一数据库上运行sql查询,以查找比该日期更新的所有记录。 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. 我该如何恢复第一个时间戳,减去30天,然后构造一个查询,并将减法的结果作为WHERE子句中的条件。 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. 我认为转换为长途旅行可能是路线,但是遇到了同样的演员问题。

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,可以从日期创建时间戳。

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

To subtract 30 days this sequence might be helpful: 要减去30天,此顺序可能会有所帮助:

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. 无论如何,我将尝试仅使用SQL执行此操作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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