我想獲取貸款和付款日期之間的日期和時間期限。我使用了PHP日期和時間函數,但它並不總是準確的。我如何在MySQL中準確地做到這一點?如何在MySQL中將給定的天數轉換爲年,月和日?
讓我們假設兩個日期,貸款拍攝日期
2009-05-24
及貸款歸還日期
2012-04-30
我寫了一個MySQL查詢
SELECT DATEDIFF('2012-04-30', '2009-05-24') `total_days`;
返回1072天,大致爲2年,11個月,12天。
請不要用PHP代碼回答,我已經試過了。這裏是 的代碼。
下面的函數使用PHP> = 5.3函數並將日期轉換爲年,月和日。
function date_interval($date1, $date2)
{
$date1 = new DateTime($date1);
$date2 = new DateTime($date2);
$interval = date_diff($date2, $date1);
return ((($y = $interval->format('%y')) > 0) ? $y . ' Year' . ($y > 1 ? 's' : '') . ', ' : '') . ((($m = $interval->format('%m')) > 0) ? $m . ' Month' . ($m > 1 ? 's' : '') . ', ' : '') . ((($d = $interval->format('%d')) > 0) ? $d . ' Day' . ($d > 1 ? 's' : '') : '');
}
以下功能使用PHP> = 5.2函數並將日期轉換爲年,月和日。
function date_interval($date1, $date2)
{
$diff = abs(strtotime($date2) - strtotime($date1));
$years = floor($diff/(365 * 60 * 60 * 24));
$months = floor(($diff - $years * 365 * 60 * 60 * 24)/(30 * 60 * 60 * 24));
$days = floor(($diff - $years * 365 * 60 * 60 * 24 - $months * 30 * 60 * 60 * 24)/(60 * 60 * 24));
return (($years > 0) ? $years . ' Year' . ($years > 1 ? 's' : '') . ', ' : '') . (($months > 0) ? $months . ' Month' . ($months > 1 ? 's' : '') . ', ' : '') . (($days > 0) ? $days . ' Day' . ($days > 1 ? 's' : '') : '');
}
有多少天有一個月? 28? 29? 30? 31? – liquorvicar
您可能需要一個存儲過程或函數才能在MySQL中執行此操作。 – liquorvicar