2009-12-09 93 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