如何使用程序樣式方法計算以下兩個日期的月數?PHP - 如何計算特定日期之後的月份數
PHP代碼。
$delete_date = "2000-01-12 08:02:39";
$current_date = date('Y-m-d H:i:s'); //current date
如何使用程序樣式方法計算以下兩個日期的月數?PHP - 如何計算特定日期之後的月份數
PHP代碼。
$delete_date = "2000-01-12 08:02:39";
$current_date = date('Y-m-d H:i:s'); //current date
$delete_date = "2000-01-12 08:02:39";
$current_date = date('Y-m-d H:i:s'); //current date
$diff = strtotime($current_date) - strtotime($delete_date);
$months = floor(floatval($diff)/(60 * 60 * 24 * 365/12));
echo $months . "\n";
我懷疑有一些邊緣情況下,這返回錯誤的值。 (每個月不是365/12天。) – 2011-01-14 19:11:42
@middaparka說什麼:這可能會導致例如在2月1日至3月2日的範圍內。但是,真的不太清楚OP的確切需求,所以它可能沒有問題 – 2011-01-14 19:13:16
好吧,這一切都取決於問題的背景。可以考慮每個月有30天還是每月365/12 = 30.41666天?另外:是否可以使用「floor」來計算幾個月?或「圓」?或者`ceil`? – scoffey 2011-01-14 19:15:33
您正在尋找DateTime::diff?
$delete_date = "2000-01-12 08:02:39";
$date_format = 'Y-m-d H:i:s';
$current_date = date($date_format);
$diff = date_diff(date_create_from_format($date_format, $delete_date), date_create());
$months = $diff->m;
沿着這條線的東西。
這是你在找什麼?
$delete_date = "2000-01-12 08:02:39";
$current_date = date('Y-m-d H:i:s'); //current date
// convert date to int
$delete_date = strtotime($delete_date);
$current_date = strtotime($current_date);
// calculate it
$diff = $delete_date - $current_date;
// convert int to time
$conv_diff = date('format', $diff);
使用日期時間,你會得到總的幾個月是這樣的:
$d1 = new DateTime("2000-01-12 08:02:39");
$d2 = new DateTime();
$d3 = $d1->diff($d2);
$months = ($d3->y*12)+$d3->m;
你仍然需要處理剩下的日子$d3->d
...但是,這取決於你的需要。
試試這個,很簡單,也許不是enogh小雞,但非常有效。
function calculateMonthsBetweenDates($fMonth, $fDay, $fYear, $tMonth, $tDay, $tYear)
{
//Build datetime vars using month, day and year
$dateFrom = mktime(0, 0, 0, $fMonth, $fDay, $fYear);
$dateTo = mktime(0, 0, 0, $tMonth, $tDay, $tYear);
//Check dateTo is a later date than dateFrom.
if($dateFrom<=$dateTo){
$yearF = date("Y", $dateFrom);
$yearT = date("Y", $dateTo);
$monthF = date("m", $dateFrom);
$monthT = date("m", $dateTo);
//same year
if ($yearF == $yearT)
$months = ($monthT - $monthF);
else{
//different year
$months = (12*($yearT-$yearF)-$monthF) + $monthT;
}
return $months;
}
else
return false; //or -1
}
你想要兩個日期之間的月數*嗎? – 2011-01-14 19:07:43
是的,這是我;我在尋找 – HELP 2011-01-14 19:08:59