2016-04-08 161 views
-2

這是一個很簡單的問題,但我無法找到解決方案。我已經在互聯網上搜索了幾天,找到了一個合適的解決方案。我知道解決方案必須簡單,但它只是我無法想象的。根據天數計算月數

 $datetimeToday = new DateTime(date('d M Y')); 
     $datetimeAccountExpirationDate= new DateTime($account->expiration_date); 
     $interval = $datetimeToday->diff($datetimeAccountExpirationDate); 
     $days = $interval->format('%R%a'); 
     $days = intval($days); 

     if($days <= 0): 
      // calculate the number of months, a month is of 30 days (for this app) 
     endif; 

我正在計算從今天開始的日期差異以及帳戶過期的那一天。如果賬戶尚未到期,我會得到一個+值,如果賬戶已過期,我會得到一個-值。然後我將它轉換爲integet,然後如果小於0,我需要計算月數,以便我可以相應地計算我的客戶的成本。在我正在開發的應用程序中,一個月的確切數字爲30 days

如下

if $days = 20 then $months = 1 // from 1 - 30, it should give 1 
    if $days = 35 then $months = 2 // from 31 - 60, it should give 2 

等它應該給的值。

編輯:

var_dump($datetimeToday->diff($datetimeAccountExpirationDate)->d); // this would give me days 
var_dump($datetimeToday->diff($datetimeAccountExpirationDate)->m); // this would return 0 for days > 0 but < 30 
+0

我建議用'的strtotime()熟悉自己;'和'日期()' – Derek

+0

您只需要使用如果你不關心月份是30天還是31天,而2月份是特別的,那麼簡單模數... – AntoineB

回答

0

這是因爲運行這樣那樣容易。

$date = "April"; 
$days_in_month = date("t", strtotime($date)); 

$date是您想要的月份的字符串表示形式。和strtotime會將其轉換爲時間戳(在本例中爲1460073600)。然後,您可以使用date並使用t設置,它將返回給定月份中的日期。這個例子會給你30中的變量$days_in_month

對於$date你可以使用任何表示的日期。例如,Feb 2016的日期會給你29天......但Feb 2015會給你28