1

嗨,我想知道我们如何将 java 中的当前日期与 mysql 中存储的日期进行比较。

存储在 MySQL 中的日期是2013-01-04 13:15:00

当我通过获取当前日期在java中比较这个日期时

Date date = new Date();

然后写一个查询,如果存储在 MySQL 中的日期小于当前显示结果。但查询返回 0 结果。

select model from abc model where model.abcStartDate >= date and model.abcEndDate >= date

在 MySQL 中,开始日期和结束日期都是时间戳数据类型。

下面是EJB实体类

@Entity
@Table(name = "abc_table", uniqueConstraints = {})
public class ABCClass implements java.io.Serializable {

private static final long serialVersionUID = -1924961655993587546L;

// Fields
private Date abcStartDate;
private Date abcEndDate;

// Constructors

/** default constructor */
public ABCClass() {
}


@OrderBy(value="3")
@Temporal(TemporalType.TIMESTAMP)
@Column(name = "abc_start_date", unique = false, nullable = false, insertable = true, updatable = true, length = 19)
public Date getabcStartDate() {
    return this.abcStartDate;
}

public void setabcStartDate(Date abcStartDate) {
    this.abcStartDate = abcStartDate;
}

@OrderBy(value="4")
@Temporal(TemporalType.TIMESTAMP)
@Column(name = "abc_end_date", unique = false, nullable = false, insertable = true, updatable = true, length = 19)
public Date getabcEndDate() {
    return this.abcEndDate;
}

public void setabcEndDate(Date abcEndDate) {
    this.abcEndDate = abcEndDate;
}

}
4

3 回答 3

1

One of right approach - use parametrized query in java Use prepared statement with query

select model from abc model where model.abcStartDate <= ? and model.abcEndDate >= ?

And then set first and second params to new Date() in your java code. In this case you can compare not only current date, but any java Date you have

于 2013-01-08T09:03:23.100 回答
1

如果要使用PreparedStatement比较 SQL 查询中的日期:

String query="select model from abc model where model.abcStartDate >= ? and model.abcEndDate <=?;";
PreparedStatement stmnt = conn.preparedStatement(query);
stmnt.setTimestamp(1, new java.sql.Timestamp(Calender.getInstance().getTime()));
stmnt.setTimestamp(2, new java.sql.Timestamp(Calender.getInstance().getTime()));
stmnt.executeQuery();
于 2013-01-08T09:30:12.057 回答
0

您必须将日期与时间进行比较:
将 java.sql.Timestamp 用于 util.Date。它会为它工作。
例如:
java.sql.Timestamp t = new Timestamp(Date.getTime());

于 2013-01-08T09:09:29.513 回答