繁体   English   中英

如何比较日期从Java到MySQL时间戳字段

[英]How to compare date from java to mysql timestamp field

抱歉再次发布此问题,但我很想知道。

我想知道我们如何比较java中的当前日期和mysql中的存储日期。

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

当我通过获取当前日期在Java中比较此日期时

Date date = new Date();

然后写一个查询,如果存储在MySQL中的日期小于当前显示的结果。 但是查询在列表中返回0结果,或者我在末尾粘贴了异常。

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

在“:?”中 在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;
}

}

并引发异常

Exception thrown from bean; nested exception is: Exception [EclipseLink-3001] (Eclipse Persistence Services - 2.2.1.v20110722-r9776): org.eclipse.persistence.exceptions.ConversionException
Exception Description: The object [65464533565], of class [class java.lang.String], could not be converted to [class java.lang.Integer].
Internal Exception: java.lang.NumberFormatException: For input string: "65464533565"

JPQL中的日期比较可以通过以下方式进行。

如果要与当前日期和时间进行比较

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

或创建查询并传递参数

query = em.createQuery("select model from abc model where model.abcStartDate >= 
:time and model.abcEndDate >= :time");
query.setParameter("time", new Date(), TemporalType.TIMESTAMP);

暂无
暂无

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

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