2009-12-09 98 views
0

只是一個匆匆的.. 如何獲得最近三月或六月的unixtime?時間戳最接近的有效一個月

如果當前的月份是2009年的二月,腳本應該給03月01日的unixtime,2009年

如果當前的月份是2009年的四月,腳本應該給2009年6月01日的unixtime。

如果當前的月份是2009年10月,腳本應該給03月01日的unixtime,2010年

感謝您的幫助!

回答

5

更新:對不起,我的壞。 「下一個」可與天,像「下個月」,而不是案件「明年三月」,因此它比原來的襯墊多一點令人費解。

strtotime()是這樣的事情真的真棒:

$tests = array(
    strtotime('2 february'), 
    strtotime('4 april'), 
    strtotime('9 november'), 
); 

foreach ($tests as $test) { 
    echo date('r', $test) . ' => ' . date('r', nextmj($test)) . "\n"; 
} 

function nextmj($time = time()) { 
    $march = strtotime('1 march', $time); 
    $june = strtotime('1 june', $time); 
    if ($march >= $time) { 
    return $march; 
    } else if ($june >= $time) { 
    return $june; 
    } else { 
    return strtotime('+1 year', $march); 
    } 
} 

輸出:

Mon, 02 Feb 2009 00:00:00 +0000 => Sun, 01 Mar 2009 00:00:00 +0000 
Sat, 04 Apr 2009 00:00:00 +0000 => Mon, 01 Jun 2009 00:00:00 +0000 
Mon, 09 Nov 2009 00:00:00 +0000 => Mon, 01 Mar 2010 00:00:00 +0000 

另見What date formats does the PHP function strtotime() support?

+0

這正是我一直在尋找!豎起大拇指的一個襯墊! – Nirmal 2009-12-09 10:10:37

+0

哎呀..但是的strtotime(「明年三月」)這種事情不工作,甚至不扔任何錯誤。 – Nirmal 2009-12-09 11:11:28

+0

哈,是解決整個查詢!謝謝。 – Nirmal 2009-12-10 01:58:23