mysql date comparison with date_format

前端 未结 3 944
遥遥无期
遥遥无期 2020-11-30 07:23

I googled and tried several ways to compare date but unfortunately didn\'t get the result as expected. I have current state of records like following:

               


        
相关标签:
3条回答
  • 2020-11-30 08:11

    Use 2012-11-02 instead of 02-11-2012 and you will not need date_format() anymore

    0 讨论(0)
  • 2020-11-30 08:21

    Your format is fundamentally not a sortable one to start with - you're comparing strings, and the string "28-10-2012" is greater than "02-11-2012".

    Instead, you should be comparing dates as dates, and then only converting them into your target format for output.

    Try this:

    select date_format(date(starttime),'%d-%m-%Y') from data
    where date(starttime) >= date '2012-11-02';
    

    (The input must always be in year-month-value form, as per the documentation.)

    Note that if starttime is a DATETIME field, you might want to consider changing the query to avoid repeated conversion. (The optimizer may well be smart enough to avoid it, but it's worth checking.)

    select date_format(date(starttime),'%d-%m-%Y') from data
    where starttime >= '2012-11-02 00:00:00';
    

    (Note that it's unusual to format a date as d-m-Y to start with - it would be better to use y-M-d in general, being the ISO-8601 standard etc. However, the above code does what you asked for in the question.)

    0 讨论(0)
  • 2020-11-30 08:27

    Use the following method :

    public function dateDiff ($date1, $date2) {
    /* Return the number of days between the two dates: */
      return round(abs(strtotime($date1)-strtotime($date2))/86400);
    }  
    /* end function dateDiff */
    

    It will help!

    0 讨论(0)
提交回复
热议问题