問題:
確定MyMy的月數是一項常見任務。然而,使用 Unix 時間戳並手動計算可能會很麻煩。
解決方案:
TIMESTAMPDIFF() 函數:
MySQL提供TIMESTAMPDIFF(>
TIMESTAMPDIFF(unit, startdate, enddate)
SELECT TIMESTAMPDIFF(MONTH, '2012-05-05', '2012-06-04') -- Outputs: 0 SELECT TIMESTAMPDIFF(MONTH, '2012-05-05', '2012-06-05') -- Outputs: 1
精確度月差:
TIMESTAMPDIFF(MONTH, startdate, enddate) + DATEDIFF(enddate, startdate + INTERVAL TIMESTAMPDIFF(MONTH, startdate, enddate) MONTH) / DATEDIFF(startdate + INTERVAL TIMESTAMPDIFF(MONTH, startdate, enddate) + 1 MONTH, startdate + INTERVAL TIMESTAMPDIFF(MONTH, startdate, enddate) MONTH)
這個公式補償了天數和閏秒年。
範例:startdate = '2012-05-05', enddate = '2012-05-27' -- Outputs: 0.7097 startdate = '2012-05-05', enddate = '2012-06-13' -- Outputs: 1.2667 startdate = '2012-02-27', enddate = '2012-06-02' -- Outputs: 3.1935
以上是如何在MySQL中有效率地計算兩個日期之間的月差?的詳細內容。更多資訊請關注PHP中文網其他相關文章!