只有在天数相同的情况下才能获得月份差异

问题描述 投票:0回答:2

如果日期相同,我怎样才能获得MySQL中两个日期之间的月份差异?这是我到目前为止所做的,但它不起作用,因为当日子不一样时,它仍然有效:

TIMESTAMPDIFF(MONTH, '2019-05-05', '2019-06-05')
Output: 1

TIMESTAMPDIFF(MONTH, '2019-05-05', '2019-06-22')
Output: 1 // should NOT work because days are 05 and 22. Needs to be the same dates

我显然可以这样做:

DAY('2019-05-05') = DAY('2019-06-05') AND TIMESTAMPDIFF(MONTH, '2019-05-05', '2019-06-05')

但我怎么能在一个功能中做到这一点?

谢谢!

php mysql date pdo timestamp
2个回答
4
投票

SUBDATE() / ADDDATE / DATE_SUB / DATE_ADD将很好地处理这个问题:

SELECT DATE_SUB('2019-06-22', INTERVAL 1 MONTH) = '2019-05-05'

| DATE_SUB('2019-06-22', INTERVAL 1 MONTH) = '2019-05-05' |
| ------------------------------------------------------: |
|                                                       0 |

SELECT DATE_SUB('2019-06-22', INTERVAL 1 MONTH) = '2019-05-22'

| DATE_SUB('2019-06-22', INTERVAL 1 MONTH) = '2019-05-22' |
| ------------------------------------------------------: |
|                                                       1 |

DBfiddle


2
投票

在MySQL中,您可以使用以下查询来获取它...

 select DATEDIFF('2019-06-22', '2019-05-05') as Diff from table_name where 
    day('2019-06-22') == day('2019-05-05');

使用列名...

 select DATEDIFF(dateColum2, dateColum1) as Diff from table_name where 
    day(dateColum2) == day(dateColum1);

从PHP你可以得到它如下...

$dateValue1 = '2019-05-05';
    $dateValue2 =  '2019-06-22';
    $time1=strtotime($dateValue1);
    $day1=date("D",$time1);

    $time2=strtotime($dateValue2);
    $day2=date("D",$time2);

    if($day1 == $day2 ) {
    $seconds_diff = $time2 - $time;
    }
© www.soinside.com 2019 - 2024. All rights reserved.