mysql日期比較

來源:互聯網
上載者:User

最簡單的用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函?悼梢?б?????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');

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.