2013-01-31 26 views
1

我想要在用戶選擇的月份的下一次出現的下一次出現時設置一個end_trial日期。即如果今天是第16位,用戶選擇第15位,我需要下個月15日的unix時間戳。但是如果今天是第14位,我需要明天的時間戳。我該如何獲得該月的某一天的下一次發生

我試過在這個SO問題Find the date for next 15th using php上找到的解決方案。

當我跑的代碼建議在這個問題和爲31

$nextnth = mktime(0, 0, 0, date('n') + (date('j') >= 31), 31); 

echo date('Y-m-d', $nextnth); 

取代15的結果是2013年3月3日

我也嘗試這一個Get the date of the next occurrence of the 18th

第二個實際上會給我2013-03-31當我跑了一個2013-1-31。

兩者都有意想不到的結果。二月是問題嗎?任何指導將不勝感激。

回答

2

這是一種方法。

function nextDate($userDay){  

    $today = date('d'); // today 

    $target = date('Y-m-'.$userDay); // target day 

    if($today <= $userDay){ 

    $return = strtotime($target); 

    } 
    else{ 

    $thisMonth = date('m') + 1; 
    $thisYear = date('Y'); 

    if($userDay >= 28 && $thisMonth == 2){ 
     $userDay = 28; 
    } 


    while(!checkdate($thisMonth,$userDay,$thisYear)){ 

    $thisMonth++; 

    if($thisMonth == 13){ 

     $thisMonth = 1; 
     $thisYear++; 

    } 

    }  

    $return = strtotime($thisYear.'-'.$thisMonth.'-'.$userDay); 

    } 

    return $return; 

} 

// usage 
echo date('Y-m-d',nextDate(29)); 

我們得到用戶的選擇並今天進行比較。

  • 如果今天小於或等於用戶選擇,我們會返回本月的時間戳。

  • 如果今天大於用戶選擇,我們會循環查看日期,並添加一個月(或一年(如果$ thisMonth命中13)。一旦這個日期確實再次存在,我們有我們的答案。

我們檢查使用php's checkdate functionstrtotimedate的日期。

+0

啊謝謝你讓我走上正軌!我確實添加了一些代碼,以防下個月是二月。很好的答案,雖然我腦海中死於盯着代碼。 – codaniel

+0

沒問題,編輯上的好的呼籲...雖然你可能想要在第一個if語句中使用相同的邏輯...因爲我猜它可能是$ userDay是2月29日,今天是2月28日,系統將假定3月1日,我不認爲這是你想要的。 :) – Dylan

+1

爲你而戰! – codaniel

0

我真的完全不明白這個問題。您可以輕鬆確定未來30天的日期,例如

$next_ts = time() + 30 * 86400; // add 30 days to current timestamp 
$next = date('Y-m-d', $next_ts); // format string as Y-m-d 
echo $next; 

如果這不是您所需要的,請說明問題。

+0

我不想要30天我想要最近的第15或第12或任何客戶選擇。 – codaniel

+0

但是最接近'2013-01-31'的'31'是什麼! – Strawberry

相關問題