开发者

Timestamp of nearest valid month

Just a quickie.. How to derive the unixtime of nearest March or June?

If the current month is February of 2009, the script should give the unixtime of March 01, 2009.

If the current month is April of 2009, the script should give the unixtime of June 01, 2009.

If 开发者_如何学Cthe current month is October of 2009, the script should give the unixtime of March 01, 2010.

Thank you for any help!


Update: Sorry, my bad. "next" works with days and in cases like "next month" but not "next March" so it's a little more convoluted than the original one liner.

strtotime() is really awesome for things like this:

$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);
  }
}

Output:

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

Also see What date formats does the PHP function strtotime() support?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜