MySQL date comparison

后端 未结 7 494
有刺的猬
有刺的猬 2020-12-18 06:30

Dates are stored in DB as such: \"2011-05-26 11:00:00\" in a datetime field. I\'d like to find all rows where the date is greater than the first of this month, ie: 2011-05-0

相关标签:
7条回答
  • 2020-12-18 06:40
    $firstDayOfMonth = date( 'Y-m-d H:i:s', mktime(0,0,0,date('n'),1,date('Y'));
    $query = "SELECT * FROM `table` WHERE `date` >= '$firstDayOfMonth'";
    
    0 讨论(0)
  • 2020-12-18 06:46

    Compare to the datetime directly:

    WHERE date_field >= '2011-05-01 00:00:00'
    
    0 讨论(0)
  • 2020-12-18 06:56

    Something like this perhaps?

    $oDateTime = new DateTime();
    $sQuery = "SELECT * FROM table WHERE date >= ".$oDateTime->format("Y-m")."-01 09:00:00";
    
    0 讨论(0)
  • 2020-12-18 06:57

    You can use TIMESTAMPDIFF function in MySQL to compare time,
    FROM_UNIXTIME function to format Unix timestamp as date.

    More mysql data and time functions and examples are available in MySQL Reference Manual date and time function .

    0 讨论(0)
  • 2020-12-18 06:59

    DATETIME fields can filtered just like integer fields, example:

    SELECT * FROM `table` WHERE `date` > '2011-05-01 09:00:00'
    

    In case you really want to convert to Unix timestamps, have a look at the UNIX_TIMESTAMP function.

    0 讨论(0)
  • 2020-12-18 07:01

    I think that you can solve it, something like this:

    firstly, create first day of month in mysql format in php

    $firsDay = date('Y-m-d 00:00:00', strtotime(date('Y-m').'-01 00:00:00'));
    

    and then, use it in the query

    select * from something where date >= $firsDay
    
    0 讨论(0)
提交回复
热议问题