在sql中對時間的操作有很多方法,我們這里總結了幾種方法,像我自己做數據庫時會把日期字段設置為int(10)這來保存日期的unix_timestamp,最后再加減比較也方便很多,因為我們用的時整型比較,有需要的朋友可以自己選擇下面任何一種方法.
最簡單的用date_format函數進行比較,代碼如下:
- select * from tb where c> date_format('2007-07-06','%Y%m%d') and c <= date_format('2007-07-09','%Y%m%d');
- select * from tb where c> date('2007-07-07') and c< date('2007-07-09')
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 < date_format('$date','%Y%m%d%H')
mysql數據庫中存的時間格式為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<date_format('"+pubtime+"','%Y-%m-%d %H:%i:%s') order by pub_time desc limit 0,1";
然后執行該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函數,比如:
- UNIX_TIMESTAMP('2008-08-08 20:08:08');
- UNIX_TIMESTAMP('2008-08-08');
返回值是整數,代碼如下:
select * from table where createtime>unix_timestamp('2011-1-1 12:12:12');
新聞熱點
疑難解答