---
title: "hql语句中支持的本地时间函数"
author: "cjnetwork"
date: "2011-11-01T16:17:35Z"
tags: []
categories: ["编程语言"]
slug: "hql"
draft: false
lastmod: "2011-11-01T16:19:10Z"
id: 1226826
url: "https://cjnetwork.iteye.com/blog/1226826"
---

hql语句中支持的本地时间函数


```

1、UNIX_TIMESTAMP()转换到秒，到1970年
2、FROM_UNIXTIME 从秒专函到时间
3、current_date()当前日期
4、current_time()当前时间
5、current_timestamp()当前时间戳
6、TO_DAYS()转换为天
7、FROM_DAYS从天转换到时间

```


例子:
1、
from Article where UNIX_TIMESTAMP(addTime) > UNIX_TIMESTAMP(current_timestamp()) - 24 * 60 * 60
2、
from Article where TO_DAYS(addTime) > TO_DAYS(current_timestamp()) - 1

注意：hql语句中不推荐使用
from Article where addTime > current_date() - 1这种写法，通常情况下是没有问题，但遇到特殊情况就会产生异常。例如当前日期为11月1号，则current_date() - 1会生成日期1970-01-01，然后条件查询的时候就查询不出来任何东西。可以写hql测试
select current_date() - 1 from Article;  其中Article为一个实体类，测试的时候，将数据库所在的服务器时间修改为某月的1号，打印查询的list返回结果集合中的一个

```

String hql = "select current_date() - 1 from Article";
List<Objcec> ret = session.createQuery(hql).setMaxResults(1).list();
if(ret.size() > 0){
	Object entry = ret.get(0);
	System.out.println(entry);
}else{
	System.out.println("null");
}

```


附：mysql支持的时间处理函数
DATE_ADD()、DATE_SUB()、TO_DAYS()、FROM_DAYS()、STR_TO_DATE()、CURRENT_TIMESTAMP()、UNIX_TIMESTAMP()、FROM_UNIXTIME()