如何将时间与database
与current time
中的内容进行匹配?
这就是我到现在为止所做的事情,但是没有成功。表中有一个名为stime
的列,其数据类型为TIME
。它的值为HH:mm:ss
String time = dateFormat.format(new java.sql.Time(new GregorianCalendar().getTimeInMillis()));
int timeattr[] = new int[2];
int i = 0;
for(String a : time.split(":")) {
timeattr[i] = Integer.parseInt(a);
i++;
}
GregorianCalendar gc = new GregorianCalendar(c.get(Calendar.YEAR), c.get(Calendar.MONTH), c.get(Calendar.DAY_OF_MONTH), timeattr[0], timeattr[1], 0);
// QUERY
String hql = "from Scheduled where stime <= :now";
List list = session.createQuery(hql).setTime("now", new java.sql.Time(gc.getTimeInMillis())).list();
Iterator iterator = list.iterator();
while(iterator.hasNext()) { // never enters the loop }
答案 0 :(得分:0)
首先,删除.setTime
调用,它没有按照您的想法执行操作。
要实际解决问题,请使用Criteria API而不是手动定义自己的HQL查询。
//Create a query that is checking columns on FooTable.
Criteria criteria = session.createCriteria(FooTable.class);
//FooTable is where stime is stored.
//Create a restriction on your query to only return records where the 'stime'
//column is less than the current system time.
criteria.add(Restrictions.lt("stime", new Time(System.currentTimeMillis()));
//return all records in a list format.
List list = criteria.list();
//iterate over your list here.
上面的代码应该替换迭代器声明之上的所有内容。
如果这不起作用,您可以发布异常/堆栈跟踪/错误消息
答案 1 :(得分:0)
使用:
String hql = "from Scheduled where stime <= CURRENT_TIME()";
应该没有所有那些混乱的计算。
在实践中,您可能需要跟踪上次执行查询的时间,以便后续调用不会获取以前的结果:
String hql = "from Scheduled where stime > :last_time AND stime <= CURRENT_TIME()";