Home  >  Article  >  Database  >  mysql日期比较

mysql日期比较

WBOY
WBOYOriginal
2016-06-07 17:51:223421browse

在sql中对时间的操作有很多方法,我们这里总结了几种方法,像我自己做数据库时会把日期字段设置为int(10)这来保存日期的unix_timestamp,最后再加减比较也方便很多,因为我们用的时整型比较哦,有需要的朋友可以自己选择下面任何一种方法。

最简单的用date_format函数进行比较

 代码如下 复制代码

* from tb where c> date_format('2007-07-06','%Y%m%d') and c


select * from tb where c> date('2007-07-07') and c


STATDAY是形如2006031001的日期数据字段

 代码如下 复制代码

select * from LOGINSTAT where STATDAY> date_format(curdate()-1,'%Y%m%d') and STATDAY >= date_format(curdate(),'%Y%m%d');

或者:

 代码如下 复制代码

select * from LOGINSTAT where STATDAY> date_format(curdate()-1,'%Y%m%d%H') and STATDAY >= date_format(curdate(),'%Y%m%d%H');

其他用法:

 代码如下 复制代码

select * from LOGINSTAT where STATDAY >= date_format('$date1','%Y%m%d%H') and STATDAY


 中存的时间格式为2008-12-28 18:08:08,现在先要从一个一个结果集rs中获得一个日期时间。我先用rs.getDate()方法试着获取时间,结果只有年月日,无法获取小时、分和秒。最后解决的方法是:

 代码如下 复制代码

      Date time1=new Date(rs.getTimestamp("pub_time").getTime());
      SimpleDateFormat formattime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
      String pubtime=formatime.format(time1);

    获得的pubtime为String型,在sql语句中用mysql的时间函数date_format('time','format')转换:

 代码如下 复制代码

    String sqlstr="select * from do_document where pub_time

    然后执行该sql语句就查到了满足条件的记录。
 

分享三

1。

 代码如下 复制代码
SELECT * FROM 表名 WHERE 字段名 BETWEEN 'YYYY-MM-1' AND 'YYYY-MM-30';

可以用日期时间函数进一步修正给出的日期
datetime和date型的数据可以直接比较,比较时datetime型的数据自动转换成date型数据.

2。函数

 代码如下 复制代码

select *
from 表
where year(日期字段名)=2007 and month(日期字段名)=6 and day(日期字段名)=10

我自己常用的是下面的方法

MySQL的UNIX_TIMESTAMP函?悼梢?б?????br /> 比如

 代码如下 复制代码

UNIX_TIMESTAMP('2008-08-08 20:08:08');
UNIX_TIMESTAMP('2008-08-08');

返回值是整?担?梢灾苯蛹?p

实例

 代码如下 复制代码

select * from table where createtime>unix_timestamp('2011-1-1 12:12:12');

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn